有没有办法让 ESLint 报告的唯一错误

Rya*_*P13 2 javascript command-line-interface typescript eslint

我正在使用 TypeScript 和 React 重构现有项目。我介绍了 ESLint,代码中报告了 300 多个错误。

这是一项相当大的任务,因为 ESLint 本身无法自动修复这些问题。

有没有办法从 ESLint CLI 输出中获取不同的错误,然后使用该规则获取引发规则错误的文件,以便我可以逐个规则而不是逐个文件地修复它?

Ale*_* L. 5

Eslint 支持自定义格式化程序。所以你可以做一些事情:

添加文件 lint-formatter.js

module.exports = results => {
  const byRuleId = results.reduce(
    (map, current) => {
      current.messages.forEach(({ ruleId, line, column }) => {
        if (!map[ruleId]) {
          map[ruleId] = [];
        }

        const occurrence = `${current.filePath}:${line}:${column}`;
        map[ruleId].push(occurrence);
      });
      return map;
    }, {}
  );

  return Object.entries(byRuleId)
    .map(([ruleId, occurrences]) => `${ruleId} (total: ${occurrences.length})\n${occurrences.join('\n')}`)
    .join('\n########################\n');
};
Run Code Online (Sandbox Code Playgroud)

上面的示例按规则 id 对错误/警告进行分组,但当然一切都在您手中。

然后使用自定义格式化程序运行 linter:

eslint -f ./lint-formatter.js
Run Code Online (Sandbox Code Playgroud)

示例输出:

object-curly-spacing (total: 2)
foo/bar.js:2:8
foo/bar.js:3:13
########################
no-trailing-spaces (total: 1)
foo/bar.js:7:11
########################
object-curly-newline (total: 2)
foo/bar.js:14:8
foo/bar.js:15:31
########################
space-infix-ops (total: 1)
foo/bar.js:18:29
Run Code Online (Sandbox Code Playgroud)