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

标签 javascript eslint

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

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

在示例情况下:

// eslint-diable-next-line no-param-reassign
param = foo;

澄清

想要我的项目中的规则,保护我们编写的所有新代码。我 不要想要手动修复所有发出违规行为的旧代码(我想要一个脚本来为我做这件事,或者如果可能的话 eslint 本身)。这就是为什么我想压制所有现有的违规行为,但尊重所有新的违规行为。我的主要目标是尽可能快地遵守新规则,以便从所有新代码中获得值(value)。我不介意旧的挥之不去的压制违规行为。

最佳答案

我在一堆 react-hooks/exhaustive-deps 上遇到了同样的问题lint 警告最终使用 json formatter以及插入 eslint 禁用注释的脚本。我跑了yarn lint . -f json -o warnings.json获取 lints 的 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);
  });
});
对我来说效果很好,虽然我希望我插入的这些评论是自动格式化的。

关于javascript - 有没有办法以编程方式逐行抑制所有 ESLint 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60629026/

相关文章:

reactjs - 如何禁用更漂亮的断线

javascript - eslint 是否只显示 fatal error ?

typescript - VSC 中的 ESLint 不适用于 .ts 和 .tsx 文件

javascript - 如何屏蔽字符串中的字母和数字

javascript - html5 getUserMedia Api 停止网络摄像头按钮不起作用

javascript - 有没有一种优雅的方式告诉 eslint 确保我们没有使用任何 ES6 语法/函数?

vue.js - Eslint Vue 3 解析错误 : '>' expected.

javascript - 放置文档就绪功能的最佳实践

JavaScript 双美元符号

javascript - 如何显示差异基于AngularJS属性的HTML?