You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Stylelint按违规规则而非文件名展示检测报告?

问题

我已在项目中实现Stylelint,但目前它按文件名展示错误信息,示例如下:

fileone.scss Line 10:5 expected this 'rule-xyz'
Line 15:5 expected this 'rule-abc'
Line 25:5 expected this 'rule-123'
anotherfile.scss Line 12:5 expected this 'rule-xyz'
Line 18:5 expected this 'rule-abc'
Line 26:5 expected this 'rule-123'

请问是否可以按违规规则而非文件名排序展示错误?期望展示形式如下:

rule-xyz
file-one.scss Line 10:5 expected bla bla
file-two.scss Line 19:5 expected bla bla
file-three.scss Line 30:5 expected bla bla
rule-abc
file-one.scss Line 10:5 expected bla bla
file-two.scss Line 19:5 expected bla bla
file-three.scss Line 30:5 expected bla bla

我已查阅Stylelint官网,但未找到相关解决方案。

解决方案

这个需求提得很实用!Stylelint本身确实没有内置按规则名称排序错误的选项,但有两种可靠的方法能实现你想要的输出格式:

1. 自定义Stylelint格式化器(推荐方案)

你可以写一个简单的Node.js脚本作为自定义格式化器,解析Stylelint的原始结果,将错误按规则名称分组,然后输出成你期望的结构。

具体步骤如下:

  1. 在项目根目录创建一个名为 rule-sorted-formatter.js 的文件:
module.exports = function (results) {
  // 按规则名称分组错误信息
  const ruleGroups = {};

  results.forEach(result => {
    const fileName = result.source;
    result.warnings.forEach(warning => {
      const ruleName = warning.rule;
      const errorLine = `${fileName} Line ${warning.line}:${warning.column} ${warning.text}`;

      if (!ruleGroups[ruleName]) {
        ruleGroups[ruleName] = [];
      }
      ruleGroups[ruleName].push(errorLine);
    });
  });

  // 将分组转换为目标输出格式
  let output = '';
  // 按规则名称字母排序
  Object.keys(ruleGroups).sort().forEach(ruleName => {
    output += `${ruleName}\n`;
    ruleGroups[ruleName].forEach(errorLine => {
      output += `${errorLine}\n`;
    });
    output += '\n'; // 规则组之间添加空行分隔
  });

  return output.trim();
};
  1. 运行Stylelint时指定这个自定义格式化器:
stylelint "**/*.scss" --custom-formatter ./rule-sorted-formatter.js

这样就能生成和你期望一致的输出,错误会按规则名称排序,每个规则下列出所有相关文件的错误信息。

2. 命令行工具组合(临时快速方案)

如果你不想编写自定义脚本,也可以用命令行工具组合来处理Stylelint的默认输出(注意这个方案相对hacky,依赖Stylelint输出格式的稳定性):

  1. 先用JSON格式化器导出结构化的检查结果:
stylelint "**/*.scss" --formatter json > stylelint-results.json
  1. 然后用jq工具(需要提前安装)解析并重新格式化JSON结果:
jq -r '
  .[] | .warnings[] | {rule: .rule, line: .line, col: .column, text: .text, file: .source}
' stylelint-results.json | sort -k1,1 | awk '
  BEGIN {prev_rule = ""}
  {
    current_rule = $1
    if (current_rule != prev_rule) {
      if (prev_rule != "") print ""
      print current_rule
      prev_rule = current_rule
    }
    $1 = ""
    print substr($0, 2)
  }
'

这个命令会将错误按规则名称排序,并以分组的形式输出。需要注意你的系统需要安装jq和awk这类工具。

内容的提问来源于stack exchange,提问作者ankitd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:51:17