最近在搭建項目框架,想着上一個項目代碼風格各異,就想着在新項目中引入Eslint來規範團隊成員代碼風格,保持統一,也方便你們維護代碼,減小沒必要要的錯誤。前端應用越發複雜,代碼規範問題必須經過強制的方式保持統一。如下是團隊逐漸摸索出的一些配置,各取所需。javascript
在用vue-cli3搭建項目的過程當中就會問你是否須要Eslint,選擇就好來。若是沒有選擇後期又想加入eslint,能夠手動安裝Eslint的相關依賴。css
npm install eslint eslint-plugin-vue --save-dev
複製代碼
須要注意:Node.js (>=6.14), npm version 3+。html
在項目根目錄下新建一個文件,名.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的校驗,能夠配置一個.eslintignore,裏面寫上須要排除的文件。vue
/build/
/config/
/dist/
/*.js
/test/unit/coverage/
複製代碼
stylelint能夠幫助咱們規範化css的書寫,風格統一,減小錯誤。java
npm i -D stylelint stylelint-config-standard stylelint-webpack-plugin
複製代碼
在項目根目錄下新建配置文件.stylelintrc.js,相關配置以下:node
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
}
};
複製代碼
雖然藉助 Eslint 來提升代碼質量,可是卻沒法保證代碼風格統一。一個統一的代碼風格對於團隊來講是頗有價值的,因此爲了達到目的,咱們使用了 Prettier在保存和提交代碼的時候,將代碼修改爲統一的風格。webpack
npm i -D prettier @vue/eslint-config-prettier
複製代碼
相關配置寫在.eslintrc.js中git
extends: ["eslint:recommended", "plugin:vue/essential", "@vue/prettier"]
複製代碼
我使用的是vscode編輯器,同時配置了vscode。es6
{
"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
複製代碼
...
"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代碼檢查。