如何在stylelint中检查选择器的最大数量?

时间:2019-03-09 08:00:36

标签: sass lint stylelint scss-lint

我需要检查一个文件中是否有一个根类。 可能吗?

// Error
.a { }
.b { }

预期

// Success
.a {}

1 个答案:

答案 0 :(得分:0)

无法通过rules built into stylelint来做到这一点。

但是,可以create a stylelint plugin进行此操作。

插件看起来像:

// ./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
  ]
}