在團隊協作中,為了統一代碼風格,避免一些低級錯誤,所以應該制定統一的規范。在Javascript中就是ESLint。下面就介紹如果在VS Code中啟用ESLint來規范VUE代碼標準。
第一步:
打開 Visual Studio Code ,首先使用快捷鍵 Ctrl + Shift + P 調出VsCode的控制臺,然后輸入下面的命令安裝ESLint插件:
ext install ESLint
第二步:
全局安裝ESLint
npm install eslint -g
第三部:
在VUE項目根目錄下創建 .eslintrc.js
代碼如下:
module.exports = {
root: true,
parser: 'babel-eslint',
parserOptions: {
sourceType: 'module'
},
env: {
browser: true,
},
// https://github.com/feross/standard/blob/master/RULES.md#javascript-standard-style
extends: 'standard',
// required to lint *.vue files
plugins: [
'html'
],
// add your custom rules here
'rules': {
// allow paren-less arrow functions
'arrow-parens': 0,
// allow async-await
'generator-star-spacing': 0,
//禁止直接使用 Object.prototypes 的內置屬性
"no-prototype-builtins":0,
// allow debugger during development
'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0,
// 強制使用有效的 JSDoc 注釋
"valid-jsdoc": 1,
"space-before-function-paren": 0,
"no-inner-declarations":0,
"no-extend-native":0// 可以使用擴展方法
}
}
第四步:
在package.json中的scripts中增加 結點
"lint": "eslint --ext .js,.vue src"
第五步:修改VS Code的配置文件
"eslint.validate": [
"javascript",
"javascriptreact",
"html",
"vue",
{
"language": "html",
"autoFix": true
}
]
到這里就可以在VS Code中看到報錯了。但是在vue運行的時候,還是沒有辦法進行eslint規范
第六步:
在build的 webpack.base.conf.js中的modules中的rules最上面的追加
{
test: /.(js|vue)$/,
loader: 'eslint-loader',
enforce: 'pre',
include: [resolve('src'), resolve('test')],
options: {
formatter: require('eslint-friendly-formatter')
}
}
最后npm run dev 就可以看到有不規范的代碼項目是沒辦法跑的。
PS: 下面附上針對此ESLint的vs code配置文件
{
"editor.codeLens": true,
"editor.fontSize": 17,
"editor.tabSize": 2,
"editor.formatOnSave": false,
"files.associations": {
"*.vue": "vue"
},
"eslint.validate": [
"javascript",
"javascriptreact",
"html",
"vue",
{
"language": "html",
"autoFix": true
}
],
"emmet.syntaxProfiles": {
"vue-html": "html",
"vue": [
"css",
"html",
"less"
]
},
"editor.fontFamily": "Source Code Pro, 'Courier New', monospace",
"files.autoSave": "off",
"editor.insertSpaces": true
}