vuecli結合eslint靜態檢查
搭建vue項目開發可能選擇vue-cli項目腳手架快速創建vue項目。(https://github.com/vuejs/vue-cli)
安裝vue-cli
npm install -g vue-cli
這種方式安裝比較慢,可以用國內淘寶鏡像安裝,cnpm,安裝cnpm
npm install -g cnpm --registry=https://registry.npm.taobao.org
繼續安裝
cnpm install -g vue-cli
vue-cli腳手架自帶webpack打包工具,創建一個基於webpack模板的新項目
vue init webpack my-project
這里需要進行一些配置,默認回車即可
This will install Vue 2.x version of the template.
For Vue 1.x use: vue init webpack#1.0 my-project
? Project name my-project
? Project description A Vue.js project
? Author runoob <test@runoob.com>
? Vue build standalone
? Use ESLint to lint your code? Yes
? Pick an ESLint preset Standard
? Setup unit tests with Karma + Mocha? Yes
? Setup e2e tests with Nightwatch? Yes
vue-cli · Generated "my-project".
To get started:
cd my-project
npm install
npm run dev
Documentation can be found at https://vuejs-templates.github.io/webpack
配置esLint
eslint配置方式主要有兩種:
- 注釋配置:使用js注釋來直接嵌入ESlint配置信息到一個文件里
- 配置文件:使用一個js,JSON或者YAML文件來給整個目錄和它的子目錄指定配置信息。這些配置可以寫成一個文件名.eslintrc.*的文件或者package.json文件里的eslintConfig項里
這兩種方式ESlint都會自動尋找然后讀取,也可以直接在命令行內指定一個配置文件。
一般需要我們去配置項包括:
- 環境:你的腳本會在哪種環境下運行。每個環境帶來了一組特定的預定義的全局變量。
- 全局變量:腳本運行期間會訪問額外的全局變量。
- 規則:使用那些規則,並且規則的等級是多少。
vue-cli腳手架安裝完成后,主要有幾個地方配置了eslint。
1,項目創建后項目中就會出現.eslintignore 和.eslintrc.js兩個文件####
.eslintignore類似Git的.gitignore用來配置不需要Eslint檢查的文件
.eslintrc.js主要用來配置具體規則
.eslintignore文件
添加不啟動靜態檢查的文件
build/*.js // 忽略build文件夾下所有的腳本文件
config/*.js
.eslintrc.js文件
// https://eslint.org/docs/user-guide/configuring
module.exports = {
root: true,
parser: 'babel-eslint', // 解析器為babel-eslint,可在package.json文件中配置
parserOptions: {
sourceType: 'module'
},
env: { //環境配置為瀏覽器
browser: true,
},
// https://github.com/standard/standard/blob/master/docs/RULES-en.md
extends: 'standard', //文件配置繼承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,
// allow debugger during development
'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0
}
}
說明: 在rules中每個配置項后面的第一個值為eslint規則的錯誤等級
- "off" 或 0 (關閉這條規則)
- "warn" 或 1 (違反規則會警告,不影響項目運行)
- "error" 或 2 (違反規則會報錯,終止項目運行)
2 在package.json文件中配置文件
"script" : {
"lint": "eslint --ext .js, .vue src"
}
"devDenpendencies" : {
"babel-eslint": "^7.1.1",
// 更多eslint文件
...
}
3 在webpack配置文件中
webpack.base.conf.js
module: {
rules: [
{
test: /\.(js|vue)$/,
loader: 'eslint-loader',
enforce: 'pre',
include: [resolve('src'), resolve('test')],
options: {
formatter: require('eslint-friendly-formatter')
}
}
]
}
有時候代碼里有些特殊情況需要我們在某一行或者某幾行關閉ESLint檢測,可以使用注釋:
1,注釋關閉所有規則
/* eslint-disable */
alert('foo');
/* eslint-enable */
2,關閉某一行的所有規則
alert('foo'); // eslint-disable-line
// eslint-disable-next-line
alert('foo');
3,在某一行關閉指定的規則
alert('foo'); // eslint-disable-line no-alert
// eslint-disable-next-line no-alert
alert('foo');
常用規則:
規則的細節請到ESLint官方網站查看 http://eslint.org/docs/rules/