Created
September 1, 2023 12:47
-
-
Save jsCommander/e2f56c754eaeec11d19f13cea4c367a0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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