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