# postcss.parse()方法
WARNING
只从例子看结果,后期会对postcss进行系统的学习
- 先搭建环境
$ npm init -y && npm i -D webpack webpack-cli postcss && touch index.scss index.js
1
- index.scss 文件内容:
div {
background: red;
.a {
color: green;
}
}
.wrap .b {
font-size: 19px;
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
- index.js 文件内容:
let postcss = require('postcss');
let fs = require('fs');
let path = require('path');
let fileCont = fs.readFileSync(path.resolve(__dirname, './index.scss'), 'utf-8');
let parseCss = postcss.parse(fileCont);
let nodes = parseCss.nodes;
console.log('-----------------------------------------------------');
console.log('文件内容:');
console.log(fileCont);
console.log('-----------------------------------------------------');
console.log('postcss 解析 css:');
console.log(parseCss);
console.log('-----------------------------------------------------');
console.log('postcss 解析 css 返回对象的 nodes 属性:');
console.log(nodes);
console.log('-----------------------------------------------------');
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
- 执行
node index.js
输出:
-----------------------------------------------------
文件内容:
div {
background: red;
.a {
color: green;
}
}
.wrap .b {
font-size: 19px;
}
-----------------------------------------------------
postcss 解析 css:
Root {
raws: { semicolon: false, after: '' },
type: 'root',
nodes:
[ Rule {
raws: [Object],
type: 'rule',
nodes: [Array],
parent: [Circular],
source: [Object],
selector: 'div' },
Rule {
raws: [Object],
type: 'rule',
nodes: [Array],
parent: [Circular],
source: [Object],
selector: '.wrap .b' } ],
source:
{ input:
Input {
css: 'div {\n background: red;\n .a {\n color: green;\n }\n}\n.wrap .b {\n font-size: 19px;\n}',
hasBOM: false,
id: '<input css 1>' },
start: { line: 1, column: 1 } } }
-----------------------------------------------------
postcss 解析 css 返回对象的 nodes 属性:
[ Rule {
raws: { before: '', between: ' ', semicolon: false, after: '\n' },
type: 'rule',
nodes: [ [Object], [Object] ],
parent:
Root {
raws: [Object],
type: 'root',
nodes: [Circular],
source: [Object] },
source: { start: [Object], input: [Object], end: [Object] },
selector: 'div' },
Rule {
raws: { before: '\n', between: ' ', semicolon: true, after: '\n' },
type: 'rule',
nodes: [ [Object] ],
parent:
Root {
raws: [Object],
type: 'root',
nodes: [Circular],
source: [Object] },
source: { start: [Object], input: [Object], end: [Object] },
selector: '.wrap .b' } ]
-----------------------------------------------------
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
WARNING