前言
最近在搭建項目框架,想着上一個項目代碼風格各異,就想着在新項目中引入Eslint來規範團隊成員代碼風格,保持統一,也方便大家維護代碼,減少不必要的錯誤。前端應用愈加複雜,代碼規範問題必須通過強制的方式保持統一。以下是團隊逐漸摸索出的一些配置,各取所需。
Eslint配置
在用vue-cli3搭建項目的過程中就會問你是否需要Eslint,選擇就好來。如果沒有選擇後期又想加入eslint,可以手動安裝Eslint的相關依賴。
安裝
npm install eslint eslint-plugin-vue --save-dev
需要注意:Node.js (>=6.14), npm version 3+。
創建Eslint配置文件
在項目根目錄下新建一個文件,名.eslintrc.js。下面是個人的一些配置,可以自行參考。
module.exports = {
root: true,
env: {
browser: true,
node: true,
es6: true
},
extends: ["eslint:recommended", "plugin:vue/essential", "@vue/prettier"],
rules: {
"generator-star-spacing": "off",
"no-console": process.env.NODE_ENV === "production" ? "warn" : "off",
"no-debugger": process.env.NODE_ENV === "production" ? "warn" : "off",
"vue/no-parsing-error": [
2,
{
"unexpected-solidus-in-tag": false
}
]
},
parserOptions: {
parser: "babel-eslint",
ecmaVersion: 7,
sourceType: "module",
ecmaFeatures: {
// 添加ES特性支持,使之能夠識別ES6語法
jsx: true
}
}
};
忽略Eslint校驗
如果一些文件不需要Eslint的校驗,可以配置一個.eslintignore,裏面寫上需要排除的文件。
/build/
/config/
/dist/
/*.js
/test/unit/coverage/
stylelint配置
stylelint可以幫助我們規範化css的書寫,風格統一,減少錯誤。
安裝依賴
npm i -D stylelint stylelint-config-standard stylelint-webpack-plugin
配置
在項目根目錄下新建配置文件.stylelintrc.js,相關配置如下:
module.exports = {
extends: "stylelint-config-standard",
rules: {
"color-no-invalid-hex": true,
"rule-empty-line-before": null,
"color-hex-length": "long",
"color-hex-case": "lower",
"unit-whitelist": ["em", "rem", "%", "s", "px"],
"declaration-colon-newline-after": null
}
};
代碼美化prettier配置
雖然藉助 Eslint 來提高代碼質量,但是卻無法保證代碼風格統一。一個統一的代碼風格對於團隊來說是很有價值的,所以爲了達到目的,我們使用了 Prettier在保存和提交代碼的時候,將代碼修改成統一的風格。
安裝依賴
npm i -D prettier @vue/eslint-config-prettier
配置
相關配置寫在.eslintrc.js中
extends: ["eslint:recommended", "plugin:vue/essential", "@vue/prettier"]
我使用的是vscode編輯器,同時配置了vscode。
{
"eslint.autoFixOnSave": true,
"eslint.validate": [
"javascript",
{
"language": "vue",
"autoFix": true
},
"html",
"vue"
],
"editor.wordWrap": "wordWrapColumn",
"editor.formatOnSave": true,
"vetur.validation.template": false,
"cSpell.ignoreWords": [
"menu",
"mixins"
]
}
推薦使用vscode的同學安裝eslint和Prettier - Code formatter這兩個插件,配合上面的配置,達到保存的時候自動格式化和校驗的目的。
提交時校驗
安裝兩個工具
- husky:一個方便用來處理 pre-commit 、 pre-push 等 githooks 的工具
- lint-staged:對 git 暫存區的代碼,運行 linters 的工具
npm i lint-staged husky -D
package.json增加配置
...
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"src/**/*.{js,jsx,vue}": [
"prettier --tab-width 2 --write",
"vue-cli-service lint --fix",
"git add"
]
}
...
這樣就可以實現在提交的時候校驗,保證錯誤的代碼無法提交。
到目前爲止,項目中就整合進了Eslint校驗,prettier美化代碼,提交hooks代碼檢查。