有没有办法以编程方式逐行抑制所有 ESLint 错误?

Red*_*ury 16 javascript eslint

如果我添加任何给定的 ESLint 规则,例如no-param-reassign在现有代码库中,我可能会遇到很多违规行为。

有没有一种好的方法可以以编程方式逐行添加对所有现有违规行为的抑制?

在示例案例中:

// eslint-diable-next-line no-param-reassign
param = foo;
Run Code Online (Sandbox Code Playgroud)

澄清

确实希望在我的项目中遵守规则,保护我们编写的所有新代码。我不想手动修复所有发出违规行为的旧代码(如果可能,我希望脚本为我执行此操作或 eslint 本身)。这就是为什么我想压制所有现有的违规行为,但尊重所有新的违规行为。我的主要目标是尽快遵守新规则,以便在所有新代码上从中获取价值。我不介意旧的挥之不去的压制违规行为。

Jon*_*eal 8

我在一堆react-hooks/exhaustive-depslint 警告中遇到了同样的问题,最终使用json 格式化程序和脚本来插入 eslint 禁用注释。我跑去yarn lint . -f json -o warnings.json获取 lint 的 json 列表,然后是这个

const json = require('./warnings.json');
const fs = require('fs');

json.forEach(({ filePath, messages, source }) => {
  // if there is no source we have nothing that needs to be eslint-ignore'd
  if (!source) {
    return;
  }

  const data = source.split('\n');

  // if the source has multiple lines which need to be eslint-ignored our offset changes per addition
  // offset is 1 because line numbers start at 1 but index numbers in an array start at 0
  let offset = 1;

  // group errors/warnings by line because we want to have one eslint disable comment with all the rules to disable
  const groupedMessages = messages.reduce((acc, next) => {
    const prevMessages = acc[next.line] ? acc[next.line] : [];
    // some lines may have the same rule twice
    const duplicateRuleForLine = prevMessages.find(message => message.ruleId === next.ruleId);
    // ignore jsx and graphql lint rules
    const applicableRule = next.ruleId && !next.ruleId.includes('jsx') && !next.ruleId.includes('graphql');

    // ignore the eslint-ignore addition for duplicates and non applicable rules
    if (duplicateRuleForLine || !applicableRule) {
      return acc;
    }

    return {
      ...acc,
      [next.line]: [...prevMessages, next],
    };
  }, {});

  Object.entries(groupedMessages).forEach(([line, messages]) => {
    // grouped ignores
    const ignore = `// eslint-disable-next-line ${messages.map(({ ruleId }) => ruleId).join(' ')}`;
    data.splice(line - offset, 0, ignore);
    offset--;
  });

  const updated = data.join('\n');

  fs.writeFile(filePath, updated, function(err) {
    if (err) return console.log(err);
  });
});
Run Code Online (Sandbox Code Playgroud)

对我来说效果很好,虽然我希望我插入的这些评论是自动格式化的。


kat*_*uke 6

我尝试了@user15185791回答的suppress-eslint-errors npm,但它不适用于ESLint8。但是,我能够从该 npm 问题中找到https://github.com/mizdra/eslint-interactive 。到目前为止,这个美妙的 npm 运行得非常完美。

执行如下命令。

yarn add -D eslint-interactive
yarn eslint-interactive src
yarn remove eslint-interactive
Run Code Online (Sandbox Code Playgroud)


小智 5

我通常使用这个: https: //github.com/amanda-mitchell/suppress-eslint-errors

为你的仓库配置 jscodemod 有点困难,但是一旦你让它工作起来就值得了。有很多强大的代码模组。