摘要
前端多人开发的时候,代码风格总是不一致,每个人的书写习惯也不同,造成了代码的可读性很低。采用eslint+husky+prettier+lint-staged方式来对前端质量进行一定程度上的提升。
1.eslint。 代码检查工具。检查代码有没有错误,有没有不和代码规范的地方。
2.prettier。代码格式化工具。
3.husky这个库,可以在 commit 之前做代码校验,如果代码有格式问题,就会禁止提交。
4.lint-staged。在你提交的文件中,执行自定义的指令。
一、安装:
安装eslint
npm i -D eslint babel-eslint eslint-config-airbnb eslint-plugin-import eslint-plugin-jsx-a11y eslint-plugin-react
安装prettier
npm install --save-dev prettier eslint-plugin-prettier eslint-config-prettier
安装 husky 和 lint-stage
yarn add husky@next # 安装最新版,就不用配置 scripts 脚本了yarn add lint-stage
二、配置
1、配置eslint
安装完eslint其实不需要什么配置,会自动生成一个配置文件,如下:
.eslintrc.js文件内容
module.exports = {
  root: true,
  parserOptions: {
    parser: ‘babel-eslint’,
    sourceType: ‘module’
  },
  env: {
    browser: true,
    node: true,
    es6: true,
  },
  “extends”: “eslint:recommended”,
  “plugins”: [
        “vue”
    ],
  // add your custom rules here
  //it is base on https://github.com/vuejs/eslint-config-vue
  rules: {
    // “no-console”: process.env.NODE_ENV === “production” ? “error” : “off”,
    // “no-debugger”: process.env.NODE_ENV === “production” ? “error” : “off”
    // “globals”: {
    //   “globalThis”: ‘readonly’
    // }
    // “vue/max-attributes-per-line”: [2, {
    //   “singleline”: 10,
    //   “multiline”: {
    //     “max”: 1,
    //     “allowFirstLine”: false
    //   }
    // }],
    // “vue/singleline-html-element-content-newline”: “off”,
    // “vue/multiline-html-element-content-newline”:”off”,
    // “vue/name-property-casing”: [“error”, “PascalCase”],
    // “vue/no-v-html”: “off”,
    // ‘accessor-pairs’: 2,
    // ‘arrow-spacing’: [2, {
    //   ‘before’: true,
    //   ‘after’: true
    // }],
    // ‘block-spacing’: [2, ‘always’],
    // ‘brace-style’: [2, ‘1tbs’, {
    //   ‘allowSingleLine’: true
    // }],
    // ‘camelcase’: [0, {
    //   ‘properties’: ‘always’
    // }],
    // ‘comma-dangle’: [2, ‘never’],
    // ‘comma-spacing’: [2, {
    //   ‘before’: false,
    //   ‘after’: true
    // }],
    // ‘comma-style’: [2, ‘last’],
    // ‘constructor-super’: 2,
    // ‘curly’: [2, ‘multi-line’],
    // ‘dot-location’: [2, ‘property’],
    // ‘eol-last’: 2,
    // ‘eqeqeq’: [“error”, “always”, {“null”: “ignore”}],
    // ‘generator-star-spacing’: [2, {
    //   ‘before’: true,
    //   ‘after’: true
    // }],
    // ‘handle-callback-err’: [2, ‘^(err|error)$’],
    // ‘indent’: [2, 2, {
    //   ‘SwitchCase’: 1
    // }],
    // ‘jsx-quotes’: [2, ‘prefer-single’],
    // ‘key-spacing’: [2, {
    //   ‘beforeColon’: false,
    //   ‘afterColon’: true
    // }],
    // ‘keyword-spacing’: [2, {
    //   ‘before’: true,
    //   ‘after’: true
    // }],
    // ‘new-cap’: [2, {
    //   ‘newIsCap’: true,
    //   ‘capIsNew’: false
    // }],
    // ‘new-parens’: 2,
    // ‘no-array-constructor’: 2,
    // ‘no-caller’: 2,
    // ‘no-console’: ‘off’,
    // ‘no-class-assign’: 2,
    // ‘no-cond-assign’: 2,
    // ‘no-const-assign’: 2,
    // ‘no-control-regex’: 0,
    // ‘no-delete-var’: 2,
    // ‘no-dupe-args’: 2,
    // ‘no-dupe-class-members’: 2,
    // ‘no-dupe-keys’: 2,
    // ‘no-duplicate-case’: 2,
    // ‘no-empty-character-class’: 2,
    // ‘no-empty-pattern’: 2,
    // ‘no-eval’: 2,
    // ‘no-ex-assign’: 2,
    // ‘no-extend-native’: 2,
    // ‘no-extra-bind’: 2,
    // ‘no-extra-boolean-cast’: 2,
    // ‘no-extra-parens’: [2, ‘functions’],
    // ‘no-fallthrough’: 2,
    // ‘no-floating-decimal’: 2,
    // ‘no-func-assign’: 2,
    // ‘no-implied-eval’: 2,
    // ‘no-inner-declarations’: [2, ‘functions’],
    // ‘no-invalid-regexp’: 2,
    // ‘no-irregular-whitespace’: 2,
    // ‘no-iterator’: 2,
    // ‘no-label-var’: 2,
    // ‘no-labels’: [2, {
    //   ‘allowLoop’: false,
    //   ‘allowSwitch’: false
    // }],
    // ‘no-lone-blocks’: 2,
    // ‘no-mixed-spaces-and-tabs’: 2,
    // ‘no-multi-spaces’: 2,
    // ‘no-multi-str’: 2,
    // ‘no-multiple-empty-lines’: [2, {
    //   ‘max’: 1
    // }],
    // ‘no-native-reassign’: 2,
    // ‘no-negated-in-lhs’: 2,
    // ‘no-new-object’: 2,
    // ‘no-new-require’: 2,
    // ‘no-new-symbol’: 2,
    // ‘no-new-wrappers’: 2,
    // ‘no-obj-calls’: 2,
    // ‘no-octal’: 2,
    // ‘no-octal-escape’: 2,
    // ‘no-path-concat’: 2,
    // ‘no-proto’: 2,
    // ‘no-redeclare’: 2,
    // ‘no-regex-spaces’: 2,
    // ‘no-return-assign’: [2, ‘except-parens’],
    // ‘no-self-assign’: 2,
    // ‘no-self-compare’: 2,
    // ‘no-sequences’: 2,
    // ‘no-shadow-restricted-names’: 2,
    // ‘no-spaced-func’: 2,
    // ‘no-sparse-arrays’: 2,
    // ‘no-this-before-super’: 2,
    // ‘no-throw-literal’: 2,
    // ‘no-trailing-spaces’: 2,
    // ‘no-undef’: 2,
    // ‘no-undef-init’: 2,
    // ‘no-unexpected-multiline’: 2,
    // ‘no-unmodified-loop-condition’: 2,
    // ‘no-unneeded-ternary’: [2, {
    //   ‘defaultAssignment’: false
    // }],
    // ‘no-unreachable’: 2,
    // ‘no-unsafe-finally’: 2,
    // ‘no-unused-vars’: [2, {
    //   ‘vars’: ‘all’,
    //   ‘args’: ‘none’
    // }],
    // ‘no-useless-call’: 2,
    // ‘no-useless-computed-key’: 2,
    // ‘no-useless-constructor’: 2,
    // ‘no-useless-escape’: 0,
    // ‘no-whitespace-before-property’: 2,
    // ‘no-with’: 2,
    // ‘one-var’: [2, {
    //   ‘initialized’: ‘never’
    // }],
    // ‘operator-linebreak’: [2, ‘after’, {
    //   ‘overrides’: {
    //     ‘?’: ‘before’,
    //     ‘:’: ‘before’
    //   }
    // }],
    // ‘padded-blocks’: [2, ‘never’],
    // ‘quotes’: [2, ‘single’, {
    //   ‘avoidEscape’: true,
    //   ‘allowTemplateLiterals’: true
    // }],
    // ‘semi’: [2, ‘never’],
    // ‘semi-spacing’: [2, {
    //   ‘before’: false,
    //   ‘after’: true
    // }],
    // ‘space-before-blocks’: [2, ‘always’],
    // ‘space-before-function-paren’: [2, ‘never’],
    // ‘space-in-parens’: [2, ‘never’],
    // ‘space-infix-ops’: 2,
    // ‘space-unary-ops’: [2, {
    //   ‘words’: true,
    //   ‘nonwords’: false
    // }],
    // ‘spaced-comment’: [2, ‘always’, {
    //   ‘markers’: [‘global’, ‘globals’, ‘eslint’, ‘eslint-disable’, ‘*package’, ‘!’, ‘,’]
    // }],
    // ‘template-curly-spacing’: [2, ‘never’],
    // ‘use-isnan’: 2,
    // ‘valid-typeof’: 2,
    // ‘wrap-iife’: [2, ‘any’],
    // ‘yield-star-spacing’: [2, ‘both’],
    // ‘yoda’: [2, ‘never’],
    // ‘prefer-const’: 2,
    // ‘no-debugger’: process.env.NODE_ENV === ‘production’ ? 2 : 0,
    // ‘object-curly-spacing’: [2, ‘always’, {
    //   objectsInObjects: false
    // }],
    // ‘array-bracket-spacing’: [2, ‘never’],
  }
}
ESLint 配置解释:
1.env: Environments,指定代码的运行环境。不同的运行环境,全局变量不一样,指明运行环境这样ESLint就能识别特定的全局变量。同时也会开启对应环境的语法支持,例如:es6。
2.parser:ESLint 默认使用Espree作为其解析器,但它并不能很好的适应 React 环境,所以刚才安装了 babel-eslint 用来代替默认的解析器,在配置里这么写”parser”: “babel-eslint”。
3.extends:ESLint 不需要自行定义大量的规则,因为很多规则已被分组作为一个规则配置。
例如:eslint:recommended就是 ESLint 的推荐规则配置,包含了ESLint的规则 里前面有✔︎的部分,recommended 规则只在ESLint升级大版本的才有可能改变。
相对的 eslint:all 是应用所有的规则,但并不推荐这么做。另外,all 规则是根据版本随时变化的。
4.plugins:顾名思义就是插件,插件是单独的npm包,命名一般以eslint-plugin开头,写的时候用字符串数组的形式,可以省略eslint-plugin开头。plugins一般包含一个或多个规则配置,可以在extends中引入。如下:
extends: [‘plugin:vue/recommended’, ‘eslint:recommended’],
5.rules:这里可以对规则进行细致的定义了,覆盖之前前面说的extends中定义的规则。
2、prettier配置
在.eslintrc.js文件的extends加入 “@vue/prettier”
extends: [“plugin:vue/essential”, “eslint:recommended”, “@vue/prettier”]
这个配置做如下三件事:
使eslint-plugin-prettier生效
不符合prettier/prettier的规则,会报错。就是之前截图中的红线。
使eslint-config-prettier生效。就是会覆盖eslint中与prettier冲突的配置。
3、husky钩子pre-commit配置
"husky": {"hooks": {"pre-commit": "lint-staged"}},"lint-staged": {"src/**/*.{js,vue}": ["eslint --fix --max-warnings 0"]}
git commit 的时候就会触发git的hooks,husky会在提交代码前,调用pre-commit钩子,执行lint-staged,如果代码不符合prettier配置的规则,会进行格式化;然后再用eslint的规则进行检查,如果有不符合规则且无法自动修复的,就会停止此次提交。如果都通过了就会讲代码添加到stage,然后commit。
我在执行git commit 的时候报错 node 不是内部命令,尝试了好几种方法最终无果,就只能用 npm run lint:fix 命令了,这个也是相当于手动执行了lint-staged这个命令。
如果想跳过校验
使用 —no-verify 指令可以跳过检验规则
git add . && git commit —no-verify -m “代码规范强制提交测试”
或者
git commit -m ‘xxx…….’ -n 
.eslintrc.js的最终配置如下:
module.exports = {root: true,parserOptions: {parser: 'babel-eslint',sourceType: 'module'},env: {browser: true,node: true,es6: true,},//"extends": "eslint:recommended",// extends: ['plugin:vue/recommended', 'eslint:recommended'],extends: ["plugin:vue/essential", "eslint:recommended", "@vue/prettier"],// add your custom rules here//it is base on https://github.com/vuejs/eslint-config-vuerules: {// "no-console": process.env.NODE_ENV === "production" ? "error" : "off",// "no-debugger": process.env.NODE_ENV === "production" ? "error" : "off"// "globals": {// "globalThis": 'readonly'// }// "vue/max-attributes-per-line": [2, {// "singleline": 10,// "multiline": {// "max": 1,// "allowFirstLine": false// }// }],// "vue/singleline-html-element-content-newline": "off",// "vue/multiline-html-element-content-newline":"off",// "vue/name-property-casing": ["error", "PascalCase"],// "vue/no-v-html": "off",// 'accessor-pairs': 2,// 'arrow-spacing': [2, {// 'before': true,// 'after': true// }],// 'block-spacing': [2, 'always'],// 'brace-style': [2, '1tbs', {// 'allowSingleLine': true// }],// 'camelcase': [0, {// 'properties': 'always'// }],// 'comma-dangle': [2, 'never'],// 'comma-spacing': [2, {// 'before': false,// 'after': true// }],// 'comma-style': [2, 'last'],// 'constructor-super': 2,// 'curly': [2, 'multi-line'],// 'dot-location': [2, 'property'],// 'eol-last': 2,// 'eqeqeq': ["error", "always", {"null": "ignore"}],// 'generator-star-spacing': [2, {// 'before': true,// 'after': true// }],// 'handle-callback-err': [2, '^(err|error)$'],// 'indent': [2, 2, {// 'SwitchCase': 1// }],// 'jsx-quotes': [2, 'prefer-single'],// 'key-spacing': [2, {// 'beforeColon': false,// 'afterColon': true// }],// 'keyword-spacing': [2, {// 'before': true,// 'after': true// }],// 'new-cap': [2, {// 'newIsCap': true,// 'capIsNew': false// }],// 'new-parens': 2,// 'no-array-constructor': 2,// 'no-caller': 2,// 'no-console': 'off',// 'no-class-assign': 2,// 'no-cond-assign': 2,// 'no-const-assign': 2,// 'no-control-regex': 0,// 'no-delete-var': 2,// 'no-dupe-args': 2,// 'no-dupe-class-members': 2,// 'no-dupe-keys': 2,// 'no-duplicate-case': 2,// 'no-empty-character-class': 2,// 'no-empty-pattern': 2,// 'no-eval': 2,// 'no-ex-assign': 2,// 'no-extend-native': 2,// 'no-extra-bind': 2,// 'no-extra-boolean-cast': 2,// 'no-extra-parens': [2, 'functions'],// 'no-fallthrough': 2,// 'no-floating-decimal': 2,// 'no-func-assign': 2,// 'no-implied-eval': 2,// 'no-inner-declarations': [2, 'functions'],// 'no-invalid-regexp': 2,// 'no-irregular-whitespace': 2,// 'no-iterator': 2,// 'no-label-var': 2,// 'no-labels': [2, {// 'allowLoop': false,// 'allowSwitch': false// }],// 'no-lone-blocks': 2,// 'no-mixed-spaces-and-tabs': 2,// 'no-multi-spaces': 2,// 'no-multi-str': 2,// 'no-multiple-empty-lines': [2, {// 'max': 1// }],// 'no-native-reassign': 2,// 'no-negated-in-lhs': 2,// 'no-new-object': 2,// 'no-new-require': 2,// 'no-new-symbol': 2,// 'no-new-wrappers': 2,// 'no-obj-calls': 2,// 'no-octal': 2,// 'no-octal-escape': 2,// 'no-path-concat': 2,// 'no-proto': 2,// 'no-redeclare': 2,// 'no-regex-spaces': 2,// 'no-return-assign': [2, 'except-parens'],// 'no-self-assign': 2,// 'no-self-compare': 2,// 'no-sequences': 2,// 'no-shadow-restricted-names': 2,// 'no-spaced-func': 2,// 'no-sparse-arrays': 2,// 'no-this-before-super': 2,// 'no-throw-literal': 2,// 'no-trailing-spaces': 2,// 'no-undef': 2,// 'no-undef-init': 2,// 'no-unexpected-multiline': 2,// 'no-unmodified-loop-condition': 2,// 'no-unneeded-ternary': [2, {// 'defaultAssignment': false// }],// 'no-unreachable': 2,// 'no-unsafe-finally': 2,// 'no-unused-vars': [2, {// 'vars': 'all',// 'args': 'none'// }],// 'no-useless-call': 2,// 'no-useless-computed-key': 2,// 'no-useless-constructor': 2,// 'no-useless-escape': 0,// 'no-whitespace-before-property': 2,// 'no-with': 2,// 'one-var': [2, {// 'initialized': 'never'// }],// 'operator-linebreak': [2, 'after', {// 'overrides': {// '?': 'before',// ':': 'before'// }// }],// 'padded-blocks': [2, 'never'],// 'quotes': [2, 'single', {// 'avoidEscape': true,// 'allowTemplateLiterals': true// }],// 'semi': [2, 'never'],// 'semi-spacing': [2, {// 'before': false,// 'after': true// }],// 'space-before-blocks': [2, 'always'],// 'space-before-function-paren': [2, 'never'],// 'space-in-parens': [2, 'never'],// 'space-infix-ops': 2,// 'space-unary-ops': [2, {// 'words': true,// 'nonwords': false// }],// 'spaced-comment': [2, 'always', {// 'markers': ['global', 'globals', 'eslint', 'eslint-disable', '*package', '!', ',']// }],// 'template-curly-spacing': [2, 'never'],// 'use-isnan': 2,// 'valid-typeof': 2,// 'wrap-iife': [2, 'any'],// 'yield-star-spacing': [2, 'both'],// 'yoda': [2, 'never'],// 'prefer-const': 2,// 'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0,// 'object-curly-spacing': [2, 'always', {// objectsInObjects: false// }],// 'array-bracket-spacing': [2, 'never'],}}
三、执行流程
配置完上述步骤,再次提交代码执行的流程如下:
待提交的代码git add 添加到暂存区;
执行 git commit;
husky注册在git pre-commit的钩子函数被调用,执行lint-staged;
lint-staged 取得所有被提交的文件依次执行写好的任务(ESLint 和 Prettier);
如果有错误(没通过ESlint检查)则停止任务,同时打印错误信息,等待修复后再执行commit;
成功commit,可push到远程
四、项目为什么要同时使用ESLint与Prettier
单单使用Prettier的问题
无代码校验很容易出现无法检查到的错误
对代码顺序无校验
对废弃方法无法快速定位
单单使用ESLint的问题
每个人写法不统一,改别人代码的时候会看着难受
用ESLint配置代码风格比较麻烦
