Skip to content

Commit 975ec52

Browse files
committed
refactor: migrate to postcss 8, close #202
1 parent 01ca621 commit 975ec52

File tree

1 file changed

+25
-29
lines changed

1 file changed

+25
-29
lines changed

src/index.js

+25-29
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
import postcss from 'postcss';
2-
31
function hasVar(string) {
42
return string.includes('var(');
53
}
@@ -8,42 +6,40 @@ function resolveValue(value, maps) {
86
return hasVar(value) ? value.replace(/var\(--.*?\)/g, match => maps[match.slice(4, -1)] || match) : value;
97
}
108

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-
299
function circularReference(maps) {
3010
return Object.keys(maps).reduce((previousMaps, property) => {
3111
previousMaps[property] = resolveValue(maps[property], maps);
3212
return previousMaps;
3313
}, maps);
3414
}
3515

36-
export default postcss.plugin('postcss-at-rules-variables', (options = {}) => {
16+
export default (options = {}) => {
3717
options = {
3818
atRules: [...new Set(['for', 'if', 'else', 'each', 'mixin', 'custom-media', ...options.atRules || ''])],
39-
variables: options.variables || {}
19+
variables: {...options.variables},
4020
};
4121

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+
}
4842
};
49-
});
43+
};
44+
45+
export const postcss = true;

0 commit comments

Comments
 (0)