摘要

前端多人开发的时候,代码风格总是不一致,每个人的书写习惯也不同,造成了代码的可读性很低。采用eslint+husky+prettier+lint-staged方式来对前端质量进行一定程度上的提升。

1.eslint。 代码检查工具。检查代码有没有错误,有没有不和代码规范的地方。

2.prettier。代码格式化工具。

3.husky这个库,可以在 commit 之前做代码校验,如果代码有格式问题,就会禁止提交。

4.lint-staged。在你提交的文件中,执行自定义的指令。

一、安装:

安装eslint

  1. npm i -D eslint babel-eslint eslint-config-airbnb eslint-plugin-import eslint-plugin-jsx-a11y eslint-plugin-react

安装prettier

  1. npm install --save-dev prettier eslint-plugin-prettier eslint-config-prettier

安装 husky 和 lint-stage

  1. yarn add husky@next # 安装最新版,就不用配置 scripts 脚本了
  2. 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配置

  1. "husky": {
  2. "hooks": {
  3. "pre-commit": "lint-staged"
  4. }
  5. },
  6. "lint-staged": {
  7. "src/**/*.{js,vue}": [
  8. "eslint --fix --max-warnings 0"
  9. ]
  10. }

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的最终配置如下:

  1. module.exports = {
  2. root: true,
  3. parserOptions: {
  4. parser: 'babel-eslint',
  5. sourceType: 'module'
  6. },
  7. env: {
  8. browser: true,
  9. node: true,
  10. es6: true,
  11. },
  12. //"extends": "eslint:recommended",
  13. // extends: ['plugin:vue/recommended', 'eslint:recommended'],
  14. extends: ["plugin:vue/essential", "eslint:recommended", "@vue/prettier"],
  15. // add your custom rules here
  16. //it is base on https://github.com/vuejs/eslint-config-vue
  17. rules: {
  18. // "no-console": process.env.NODE_ENV === "production" ? "error" : "off",
  19. // "no-debugger": process.env.NODE_ENV === "production" ? "error" : "off"
  20. // "globals": {
  21. // "globalThis": 'readonly'
  22. // }
  23. // "vue/max-attributes-per-line": [2, {
  24. // "singleline": 10,
  25. // "multiline": {
  26. // "max": 1,
  27. // "allowFirstLine": false
  28. // }
  29. // }],
  30. // "vue/singleline-html-element-content-newline": "off",
  31. // "vue/multiline-html-element-content-newline":"off",
  32. // "vue/name-property-casing": ["error", "PascalCase"],
  33. // "vue/no-v-html": "off",
  34. // 'accessor-pairs': 2,
  35. // 'arrow-spacing': [2, {
  36. // 'before': true,
  37. // 'after': true
  38. // }],
  39. // 'block-spacing': [2, 'always'],
  40. // 'brace-style': [2, '1tbs', {
  41. // 'allowSingleLine': true
  42. // }],
  43. // 'camelcase': [0, {
  44. // 'properties': 'always'
  45. // }],
  46. // 'comma-dangle': [2, 'never'],
  47. // 'comma-spacing': [2, {
  48. // 'before': false,
  49. // 'after': true
  50. // }],
  51. // 'comma-style': [2, 'last'],
  52. // 'constructor-super': 2,
  53. // 'curly': [2, 'multi-line'],
  54. // 'dot-location': [2, 'property'],
  55. // 'eol-last': 2,
  56. // 'eqeqeq': ["error", "always", {"null": "ignore"}],
  57. // 'generator-star-spacing': [2, {
  58. // 'before': true,
  59. // 'after': true
  60. // }],
  61. // 'handle-callback-err': [2, '^(err|error)$'],
  62. // 'indent': [2, 2, {
  63. // 'SwitchCase': 1
  64. // }],
  65. // 'jsx-quotes': [2, 'prefer-single'],
  66. // 'key-spacing': [2, {
  67. // 'beforeColon': false,
  68. // 'afterColon': true
  69. // }],
  70. // 'keyword-spacing': [2, {
  71. // 'before': true,
  72. // 'after': true
  73. // }],
  74. // 'new-cap': [2, {
  75. // 'newIsCap': true,
  76. // 'capIsNew': false
  77. // }],
  78. // 'new-parens': 2,
  79. // 'no-array-constructor': 2,
  80. // 'no-caller': 2,
  81. // 'no-console': 'off',
  82. // 'no-class-assign': 2,
  83. // 'no-cond-assign': 2,
  84. // 'no-const-assign': 2,
  85. // 'no-control-regex': 0,
  86. // 'no-delete-var': 2,
  87. // 'no-dupe-args': 2,
  88. // 'no-dupe-class-members': 2,
  89. // 'no-dupe-keys': 2,
  90. // 'no-duplicate-case': 2,
  91. // 'no-empty-character-class': 2,
  92. // 'no-empty-pattern': 2,
  93. // 'no-eval': 2,
  94. // 'no-ex-assign': 2,
  95. // 'no-extend-native': 2,
  96. // 'no-extra-bind': 2,
  97. // 'no-extra-boolean-cast': 2,
  98. // 'no-extra-parens': [2, 'functions'],
  99. // 'no-fallthrough': 2,
  100. // 'no-floating-decimal': 2,
  101. // 'no-func-assign': 2,
  102. // 'no-implied-eval': 2,
  103. // 'no-inner-declarations': [2, 'functions'],
  104. // 'no-invalid-regexp': 2,
  105. // 'no-irregular-whitespace': 2,
  106. // 'no-iterator': 2,
  107. // 'no-label-var': 2,
  108. // 'no-labels': [2, {
  109. // 'allowLoop': false,
  110. // 'allowSwitch': false
  111. // }],
  112. // 'no-lone-blocks': 2,
  113. // 'no-mixed-spaces-and-tabs': 2,
  114. // 'no-multi-spaces': 2,
  115. // 'no-multi-str': 2,
  116. // 'no-multiple-empty-lines': [2, {
  117. // 'max': 1
  118. // }],
  119. // 'no-native-reassign': 2,
  120. // 'no-negated-in-lhs': 2,
  121. // 'no-new-object': 2,
  122. // 'no-new-require': 2,
  123. // 'no-new-symbol': 2,
  124. // 'no-new-wrappers': 2,
  125. // 'no-obj-calls': 2,
  126. // 'no-octal': 2,
  127. // 'no-octal-escape': 2,
  128. // 'no-path-concat': 2,
  129. // 'no-proto': 2,
  130. // 'no-redeclare': 2,
  131. // 'no-regex-spaces': 2,
  132. // 'no-return-assign': [2, 'except-parens'],
  133. // 'no-self-assign': 2,
  134. // 'no-self-compare': 2,
  135. // 'no-sequences': 2,
  136. // 'no-shadow-restricted-names': 2,
  137. // 'no-spaced-func': 2,
  138. // 'no-sparse-arrays': 2,
  139. // 'no-this-before-super': 2,
  140. // 'no-throw-literal': 2,
  141. // 'no-trailing-spaces': 2,
  142. // 'no-undef': 2,
  143. // 'no-undef-init': 2,
  144. // 'no-unexpected-multiline': 2,
  145. // 'no-unmodified-loop-condition': 2,
  146. // 'no-unneeded-ternary': [2, {
  147. // 'defaultAssignment': false
  148. // }],
  149. // 'no-unreachable': 2,
  150. // 'no-unsafe-finally': 2,
  151. // 'no-unused-vars': [2, {
  152. // 'vars': 'all',
  153. // 'args': 'none'
  154. // }],
  155. // 'no-useless-call': 2,
  156. // 'no-useless-computed-key': 2,
  157. // 'no-useless-constructor': 2,
  158. // 'no-useless-escape': 0,
  159. // 'no-whitespace-before-property': 2,
  160. // 'no-with': 2,
  161. // 'one-var': [2, {
  162. // 'initialized': 'never'
  163. // }],
  164. // 'operator-linebreak': [2, 'after', {
  165. // 'overrides': {
  166. // '?': 'before',
  167. // ':': 'before'
  168. // }
  169. // }],
  170. // 'padded-blocks': [2, 'never'],
  171. // 'quotes': [2, 'single', {
  172. // 'avoidEscape': true,
  173. // 'allowTemplateLiterals': true
  174. // }],
  175. // 'semi': [2, 'never'],
  176. // 'semi-spacing': [2, {
  177. // 'before': false,
  178. // 'after': true
  179. // }],
  180. // 'space-before-blocks': [2, 'always'],
  181. // 'space-before-function-paren': [2, 'never'],
  182. // 'space-in-parens': [2, 'never'],
  183. // 'space-infix-ops': 2,
  184. // 'space-unary-ops': [2, {
  185. // 'words': true,
  186. // 'nonwords': false
  187. // }],
  188. // 'spaced-comment': [2, 'always', {
  189. // 'markers': ['global', 'globals', 'eslint', 'eslint-disable', '*package', '!', ',']
  190. // }],
  191. // 'template-curly-spacing': [2, 'never'],
  192. // 'use-isnan': 2,
  193. // 'valid-typeof': 2,
  194. // 'wrap-iife': [2, 'any'],
  195. // 'yield-star-spacing': [2, 'both'],
  196. // 'yoda': [2, 'never'],
  197. // 'prefer-const': 2,
  198. // 'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0,
  199. // 'object-curly-spacing': [2, 'always', {
  200. // objectsInObjects: false
  201. // }],
  202. // 'array-bracket-spacing': [2, 'never'],
  203. }
  204. }

三、执行流程
配置完上述步骤,再次提交代码执行的流程如下:

待提交的代码git add 添加到暂存区;
执行 git commit;
husky注册在git pre-commit的钩子函数被调用,执行lint-staged;
lint-staged 取得所有被提交的文件依次执行写好的任务(ESLint 和 Prettier);
如果有错误(没通过ESlint检查)则停止任务,同时打印错误信息,等待修复后再执行commit;
成功commit,可push到远程
四、项目为什么要同时使用ESLint与Prettier
单单使用Prettier的问题
无代码校验很容易出现无法检查到的错误
对代码顺序无校验
对废弃方法无法快速定位
单单使用ESLint的问题
每个人写法不统一,改别人代码的时候会看着难受
用ESLint配置代码风格比较麻烦