eslint是 js的代碼檢查工具, 規範常用的js代碼規範
eslint 配置項
- root 限定配置檔案的使用範圍
- parser 指定eslint的解析器
- parserOptions 設定解析器選項
- extends 指定eslint規範
- plugins 引用第三方的插件
- env 指定代碼運作的宿主環境
- rules 啟用額外的規則或覆寫預設的規則
- globals 聲明在代碼中的自定義全局變量
配置檔案
- webpack.base.conf.js
rules 中添加
{
test: /\.js$/,
loader: 'eslint-loader',
enforce: "pre",
include: [resolve('src')], // 指定檢查的目錄
options: { // 這裡的配置項參數将會被傳遞到 eslint 的 CLIEngine
formatter: require('eslint-friendly-formatter') // 指定錯誤報告的格式規範
}
}
其中 resolve為函數
function resolve (dir) {
return path.join(__dirname, '..', dir)
}
- eslint忽略檔案 .eslintignore
這個根據項目中的具體情況來把,比如
/build/
/config/
/dist/
/*.js
- eslint具體規則
個人喜好把, 我自己定義了一些規則
參照官網 https://eslint.org/docs/user-guide/configuring
module.exports = {
root: true,
parser: 'babel-eslint',
parserOptions: {
sourceType: 'module'
},
plugins: ['html'],
settings: {
'html/html-extensions': ['.html', '.vue'],
'html/indent': '+2',
},
extends: 'standard',
env: {
browser: true,
},
//off 0 關閉規則
//warn 1 開啟規則,使用警告
//error 2 開啟規則,使用錯誤
rules: {
// "semi": ["error", "always"],
"linebreak-style": [2, "windows"],
"arrow-parens": 0,
'indent': ["off", "tab"],
"space-before-function-paren": [2, "never"], //禁止在參數的 ( 前面有空格。
// allow debugger during development
"no-debugger": process.env.NODE_ENV === 'production' ? 'error' : 'off',
"no-console": process.env.NODE_ENV === 'production' ? 1 : 0
}
}
依賴包
從webpack.base.conf.js中的配置可得到需要安裝的node依賴有
- eslint
- babel-eslint
- eslint-friendly-formatter
至于其他的根據提示一步一步的安裝就可以了
最終需要安裝的依賴有
npm i babel-eslint eslint eslint-config-standard eslint-friendly-formatter eslint-loader eslint-plugin-html eslint-plugin-import eslint-plugin-node eslint-plugin-promise eslint-plugin-standard --save-dev