Move all code under the Once event

Apparently the other events are common to all plugins.
This commit is contained in:
RMidhunSuresh 2022-03-07 11:32:30 +05:30
parent 60d60e9572
commit 92084e8005

View file

@ -1,4 +1,4 @@
import { Color } from "color";
const Color = require("color");
let aliasMap;
let resolvedMap;
@ -44,31 +44,8 @@ function extractAlias(decl) {
}
}
/* *
* @type {import('postcss').PluginCreator}
*/
module.exports = (opts = {}) => {
aliasMap = new Map();
resolvedMap = new Map();
const { variables } = opts;
return {
postcssPlugin: "postcss-compile-variables",
Once(root) {
/*
Go through the CSS file once to extract all aliases.
We use the extracted alias when resolving derived variables
later.
*/
root.walkDecls(decl => extractAlias(decl));
},
Declaration(declaration) {
resolveDerivedVariable(declaration, variables);
},
OnceExit(root, { Rule, Declaration }) {
const newRule = new Rule({ selector: ":root", source: root.source })
function addResolvedVariablesToRootSelector( root, variables, { Rule, Declaration }) {
const newRule = new Rule({ selector: ":root", source: root.source });
// Add base css variables to :root
for (const [key, value] of Object.entries(variables)) {
const declaration = new Declaration({ prop: `--${key}`, value });
@ -80,6 +57,27 @@ module.exports = (opts = {}) => {
newRule.append(declaration);
});
root.append(newRule);
}
/* *
* @type {import('postcss').PluginCreator}
*/
module.exports = (opts = {}) => {
aliasMap = new Map();
resolvedMap = new Map();
const { variables } = opts;
return {
postcssPlugin: "postcss-compile-variables",
Once(root, {Rule, Declaration}) {
/*
Go through the CSS file once to extract all aliases.
We use the extracted alias when resolving derived variables
later.
*/
root.walkDecls(decl => extractAlias(decl));
root.walkDecls(decl => resolveDerivedVariable(decl, variables));
addResolvedVariablesToRootSelector(root, variables, { Rule, Declaration });
},
};
};