1
- import postcss from 'postcss' ;
2
-
3
1
function hasVar ( string ) {
4
2
return string . includes ( 'var(' ) ;
5
3
}
@@ -8,42 +6,40 @@ function resolveValue(value, maps) {
8
6
return hasVar ( value ) ? value . replace ( / v a r \( - - .* ?\) / g, match => maps [ match . slice ( 4 , - 1 ) ] || match ) : value ;
9
7
}
10
8
11
- function getProperty ( nodes ) {
12
- let propertys = { } ;
13
-
14
- nodes . walkRules ( rule => {
15
- if ( rule . selector !== ':root' ) {
16
- return ;
17
- }
18
-
19
- rule . each ( ( { type, prop : property , value} ) => {
20
- if ( type === 'decl' ) {
21
- propertys [ property ] = value ;
22
- }
23
- } ) ;
24
- } ) ;
25
-
26
- return propertys ;
27
- }
28
-
29
9
function circularReference ( maps ) {
30
10
return Object . keys ( maps ) . reduce ( ( previousMaps , property ) => {
31
11
previousMaps [ property ] = resolveValue ( maps [ property ] , maps ) ;
32
12
return previousMaps ;
33
13
} , maps ) ;
34
14
}
35
15
36
- export default postcss . plugin ( 'postcss-at-rules-variables' , ( options = { } ) => {
16
+ export default ( options = { } ) => {
37
17
options = {
38
18
atRules : [ ...new Set ( [ 'for' , 'if' , 'else' , 'each' , 'mixin' , 'custom-media' , ...options . atRules || '' ] ) ] ,
39
- variables : options . variables || { }
19
+ variables : { ... options . variables } ,
40
20
} ;
41
21
42
- return nodes => {
43
- const maps = circularReference ( Object . assign ( getProperty ( nodes ) , options . variables ) ) ;
44
-
45
- nodes . walkAtRules ( new RegExp ( options . atRules . join ( '|' ) ) , rules => {
46
- rules . params = resolveValue ( rules . params , maps ) ;
47
- } ) ;
22
+ return {
23
+ postcssPlugin : 'postcss-at-rules-variables' ,
24
+ prepare ( ) {
25
+ let variables = { } ;
26
+ return {
27
+ Declaration ( node ) {
28
+ if ( node . variable ) {
29
+ variables [ node . prop ] = node . value ;
30
+ }
31
+ } ,
32
+ Once ( ) {
33
+ variables = circularReference ( Object . assign ( variables , options . variables ) ) ;
34
+ } ,
35
+ AtRule ( rule ) {
36
+ if ( options . atRules . includes ( rule . name ) ) {
37
+ rule . params = resolveValue ( rule . params , variables ) ;
38
+ }
39
+ }
40
+ } ;
41
+ }
48
42
} ;
49
- } ) ;
43
+ } ;
44
+
45
+ export const postcss = true ;
0 commit comments