使用 ESLint 的 --fix 标志

ESLint 的--fix选项告诉 ESLint 修复代码中任何它知道如何修复的错误。

例如,ESLint 推荐的配置使用了 no-extra-boolean-cast 规则,这将在 if 语句中删除不必要 !!。例如,假设您有以下 test.js 文件。因为 JavaScript if 语句已经检查了 truthy 值,所以在 if 语句中没有必要使用 !!

if (!!(typeof window === 'undefined')) {
  console.log('Hello from Node.js!')
}

假设您有以下 .eslintrc.json 配置文件:

{ 
  "parserOptions": {
    "ecmaVersion": 2020
  },
  "rules": {
    "no-extra-boolean-cast": "error"
  }
}

ESLint 会报 Redundant double negation 错误:

$ ./node_modules/.bin/eslint ./test.js 

/scratch/test.js
  1:5  error  Redundant double negation  no-extra-boolean-cast

✖ 1 problem (1 error, 0 warnings)
  1 error and 0 warnings potentially fixable with the `--fix` option.

$ cat ./test.js 

注意 1 error and 0 warnings potentially fixable with the --fix option 这一行。这说明 ESLint 知道如何修复这个错误。运行 ./node_modules/.bin/eslint --fix ./test.js,这个错误就会消失。

$ ./node_modules/.bin/eslint --fix ./test.js 
$ cat ./test.js

if (typeof window === 'undefined') {
  console.log('Hello from Node.js!');
}

请注意,ESLint 删除了不必要的 !!

ESLint 只能自动修复某些 ESLint 规则的违规行为。ESLint 有一个完整的内置 ESLint 规则列表,并解释了它可以自动应用修复的规则。

使用 npm 脚本

我们添加一个 npm scripts 来运行 ESLint 规则。

例如,假设您的 package.json 文件包含以下行:

{
  "scripts": {
    "lint:fix": "eslint . --fix"
  }
}

现在,您只需要在命令行运行 npm run lint:fix,它将修复它可修复的内容。

全部评论

相关推荐

11-14 21:41
已编辑
门头沟学院 Java
牛客54175811...:今年对双非很难。1、争取一段大厂实习经历,2、狂磕八股,3、再跑个难度提升的项目。
点赞 评论 收藏
分享
notbeentak...:孩子,说实话,选择很重要,可能你换一个方向会好很多,但是现在时间不太够了,除非准备春招
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务