node最佳实践9-代码风格eslint

315 阅读4分钟

项目本地安装

$ npm i eslint -D

全局安装

$ npm i eslint -g

全局安装的话可直接使用eslint --init 开始初始化配置,如果是本地安装的可以执行

 ./node_modules/.bin/eslint --init
// 或者 npx eslint --init
// 或者  npm init @eslint/config

以问答形式创建配置文件:

(base) ➜  node-demo git:(main) ✗ npx eslint --init
You can also run this command directly using 'npm init @eslint/config'.
Need to install the following packages:
  @eslint/create-config
Ok to proceed? (y) y
✔ How would you like to use ESLint? · problems
✔ What type of modules does your project use? · esm
✔ Which framework does your project use? · none
✔ Does your project use TypeScript? · No / Yes
✔ Where does your code run? · browser, node
✔ What format do you want your config file to be in? · JavaScript
Successfully created .eslintrc.js file in /Users/dongzhiqin/myProjects/node-demo

为了支持动态配置,这里选择js格式的配置文件

module.exports = {
    "env": {
        "browser": true,
        "es2021": true,
        "node": true
    },
    "extends": "eslint:recommended",
    "parserOptions": {
        "ecmaVersion": "latest",
        "sourceType": "module"
    },
    "rules": {
    }
}

此时如果添加一条规则

"rules": {
  "semi": ["warn","never"]
}

执行npx eslint src,对src文件夹内的文件进行规范检查,会发现有Extra semicolon的警报,而且不出意外还有never used的错误提示

/Users/dongzhiqin/myProjects/node-demo/src/routes/index.route.js
   4:30  warning  Extra semicolon                   semi
   7:36  error    'next' is defined but never used  no-unused-vars
   8:44  warning  Extra semicolon                   semi
   9:3   warning  Extra semicolon                   semi
  10:47  error    'next' is defined but never used  no-unused-vars
  13:3   warning  Extra semicolon                   semi
  14:42  error    'next' is defined but never used  no-unused-vars
  20:19  warning  Extra semicolon                   semi
  21:9   warning  Extra semicolon                   semi

有些warning使用vscode的eslint插件的保存自动修复功能可以很快修复

"rules": {
  "indent": [2,"tab"]
}
// 添加这个规则后保存,vscode自动把eslintrc.js文件调整为tab缩进模式

eslintrc的一个示例

{
  "env": {
    "node": true,
    "browser": true
  },
  "globals": {
    "exampleGlobalVariable": true
  },
  "rules": {
    "no-console": 0,
    "space-infix-ops": "error",
    "quotes": ["error", "single", {
      "avoidEscape": true,
      "allowTemplateLiterals": true
    }],
    "space-before-blocks": ["error", "always"],
    "semi": ["error", "never"]
  },
  "plugins": []
}
  • parse — 指定解析器
  • parserOptions — 指定解析器选项
  • env — 指定脚本的运行环境
  • root — 为 true 时,停止向上查找父级目录中的配置文件
  • globals — 脚本在执行期间访问的额外的全局变量
  • rules — 在此处添加您的自定义规则

其他更多规则参考eslint规则中文版

  • "off" 或 0 - 关闭规则
  • "warn" 或 1 - 开启规则,使用警告级别的错误:warn (不会导致程序退出)
  • "error" 或 2 - 开启规则,使用错误级别的错误:error (当被触发的时候,程序会退出)
"rules": {
    "indent": [
        "error",
        "tab"
    ],
    "linebreak-style": [
        "error",
        "windows"
    ],
    "quotes": [
        "error",
        "single"        // 改成字符串必须由单引号括起来而不是双引号,'string'不报错,"string"报错
    ],
    "semi": [
        "error",
        "never"         // 改成代码结尾不再加分号,加了分号报错,不加分号不报错
    ],
    "no-unused-vars": 0 // 0 相当于 off,表示关闭规则,相当于不再校验这条规则:变量定义了必须使用
}

ESLint 个人并不提倡任何编码风格。您可以设置 .eslintrc 文件以使用您喜欢的样式规则强制编码样式。

还可以将 ESLint 与样式指南(如 AirbnbJavaScript 标准风格)一起使用。

你还必须使用额外的插件,例如:

为了方便运行,可以在package.json里面添加脚本

"scripts": {
  "lint": "npx eslint src",
  "lint-fix": "npx eslint src --fix"
}

配置脚本后可直接执行npm run lint来进行代码检查,执行npx run lint-fix

eslintignore

eslintignore用来配置一些不想要进行代码规范检查的文件

**/migrations/*.js
**/seeders/*.js

配合husky使用

npx husky add .husky/pre-commit "npm run lint"

这样我们在执行 git commit 的同时,就会首先进行 ESLint 校验,如果校验不通过就无法提交

52 problems (52 errors, 0 warnings)
  29 errors and 0 warnings potentially fixable with the `--fix` option.

husky - pre-commit hook exited with code 1 (error)

待修改完不合规的代码后才可以提交。

略过eslint

/* eslint-disable */ // 下面的代码关闭代码规范检查

const apple = "apple";  // eslint-disable-line  // 关闭单行检查

/* eslint-enable */  // 下面的代码开启代码规范检查

// eslint-disable-next-line  // 关闭下一行的代码规范检查

// eslint-disable no-console, no-control-regex // 关闭特定的代码规范
console.log('JavaScript debug log');
console.log('eslint is disabled now');

lint-staged

lint-staged 是一个在git暂存文件上运行linters的工具,用于缩小eslint的检查范围,把范围限制在修改过的文件,减少检查的运行时间。

npm i lint-staged -D

通过在package.json中添加指令来安排lint-staged要怎么干活

{
  "lint-staged":{
    "src/**/*.js": ["npx eslint --cache --fix --no-ignore"]  
  }
}

这里对暂存区内src文件夹下的js文件进行代码规范检查,并且只对改变的文件进行检查(cache),不包含已忽略(eslintignore)的文件。

有的项目会在lint-staged里面使用prettier进行代码规范检查

npm i lint-staged prettier -D // 必须安装prettier

//package.json
  "lint-staged": {
    "src/**/*.{js,vue}": [      "prettier --write",      "eslint --fix",      "git add"    ]
  }
 // 在版本10之前,git add作为最后一步,必须手动包含任务。

结合husky进行使用,修改pre-commit

#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

echo "before commit"
# npm run lint
npx lint-staged

参考

如何在node中使用eslint

how to disable eslint

打造eslint工作流

eslint官方中文文档

eslint规则中文版

lint-staged使用教程

husky+lint-staged助力团队代码规范