I need to check that there is one root class in one file. Is it possible?
// Error
.a { }
.b { }
Expected
// Success
.a {}
It is not possible to do this with the rules built into stylelint.
However, it is possible to create a stylelint plugin to do this.
The plugin would look something like:
// ./plugins/stylelint-root-max-rules/index.js
const isNumber = require("lodash/isNumber");
const {
createPlugin,
utils: { report, ruleMessages, validateOptions }
} = require("stylelint");
const ruleName = "plugin/root-max-rules";
const messages = ruleMessages(ruleName, {
expected: max =>
`Expected no more than ${max} ${max === 1 ? "rule" : "rules"}`
});
const rule = quantity => {
return (root, result) => {
const validOptions = validateOptions(result, ruleName, {
actual: quantity,
possible: isNumber
});
if (!validOptions) return;
const { length } = root.nodes.filter(node => node.type === "rule");
if (length <= quantity) return;
report({
message: messages.expected(quantity),
node: root,
result,
ruleName
});
};
};
module.exports = createPlugin(ruleName, rule);
module.exports.ruleName = ruleName;
module.exports.messages = messages;
You would then use the plugin like so:
{
"plugins": ["./plugins/stylelint-root-max-rules"],
"rules": [
"plugin/root-max-rules": 1
]
}