我需要检查一个文件中是否有一个根类。可能吗?
// Error
.a { }
.b { }
预期的
// Success
.a {}
使用stylelint 内置的规则是不可能做到这一点的。
但是,可以创建一个 stylelint 插件来执行此操作。
该插件看起来像:
// ./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;
然后,您将像这样使用插件:
{
"plugins": ["./plugins/stylelint-root-max-rules"],
"rules": [
"plugin/root-max-rules": 1
]
}