Skip to content

Instantly share code, notes, and snippets.

@willsmanley
Created February 27, 2024 19:50
Show Gist options
  • Save willsmanley/09480d82680ff671e6bd1edfd7dab633 to your computer and use it in GitHub Desktop.
Save willsmanley/09480d82680ff671e6bd1edfd7dab633 to your computer and use it in GitHub Desktop.
const stylelint = require('stylelint');
const valueParser = require('postcss-value-parser');
const ruleName = 'plugin/valid-css-var';
const messages = stylelint.utils.ruleMessages(ruleName, {
expected: (variable) => `Expected "${variable}" to be a valid CSS variable`,
});
module.exports = stylelint.createPlugin(ruleName, (primaryOption, secondaryOptions, context) => {
return (root, result) => {
const validOptions = stylelint.utils.validateOptions(result, ruleName, {
// Validation options if any
});
if (!validOptions) {
return;
}
root.walkDecls((decl) => {
const value = decl.value;
// Parse the value to find variables
const parsedValue = valueParser(value);
parsedValue.walk((node) => {
if (node.type === 'function' && node.value === 'var') {
// Example check: ensure the variable is defined
const variableName = node.nodes[0].value;
if (!isValidVariable(variableName, root)) {
stylelint.utils.report({
ruleName,
result,
node: decl,
message: messages.expected(variableName),
});
}
}
});
});
};
});
function isValidVariable(variableName, root) {
// Implement logic to check if variable is valid.
// This could involve checking if the variable is defined in the :root selector
// or checking against a list of known valid variables.
let isValid = false;
// Example: Checking for variable definition in :root
root.walkRules(':root', (rule) => {
rule.walkDecls(`--${variableName}`, (decl) => {
isValid = true;
});
});
return isValid;
}
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