Skip to content

Instantly share code, notes, and snippets.

@jsCommander
Created September 1, 2023 12:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsCommander/e2f56c754eaeec11d19f13cea4c367a0 to your computer and use it in GitHub Desktop.
Save jsCommander/e2f56c754eaeec11d19f13cea4c367a0 to your computer and use it in GitHub Desktop.
// eslint-disable-next-line node/no-unpublished-require
const stylelint = require('stylelint');
const ruleName = 'css-vars';
const messages = stylelint.utils.ruleMessages(ruleName, {
undefinedCssVar: variable => `Expected variable to be defined: ${variable}`,
});
const regex = /--[\w-]+/g;
const definedVars = new Set();
const plugin = stylelint.createPlugin(ruleName, isEnabled => (root, result) => {
if (!isEnabled) {
return;
}
root.walkDecls(decl => {
if (decl.prop.startsWith('--')) {
definedVars.add(decl.prop);
}
});
root.walkDecls(decl => {
const matches = decl.value.match(regex) || [];
if (matches.length === 0) {
return;
}
matches.forEach(cssVar => {
if (!definedVars.has(cssVar)) {
stylelint.utils.report({
message: messages.undefinedCssVar(cssVar),
node: decl,
result,
ruleName,
});
}
});
});
});
module.exports = plugin;
module.exports.ruleName = ruleName;
module.exports.messages = messages;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment