给项目添加 ESlint代码风格检查

3,588 阅读2分钟

中文快速查找:直接用浏览器的 Commond + F 搜索会更快捷

eslint.bootcss.com/docs/rules/


1.安装eslint ,目前安装的是 eslint 4.15.0版本

npm install eslint --save-dev

2. 如果全局没安装,执行一下命令初始化eslint

./node_modules/.bin/eslint --init
选择 模式的时候选择 standard 标准模式(还有google,airbnb)会自动安装一下plugin,安装失败的话,可以手动单个plugin 安装, 还需要安装 eslint-plugin-vue 插件
"babel-eslint": "^10.1.0",
"eslint-plugin-import": "^2.20.1",
"eslint-plugin-node": "^11.0.0",
"eslint-plugin-promise": "^4.2.1",
"eslint-plugin-standard": "^4.0.1",
"eslint-plugin-vue": "^6.2.2",


3.安装之后就要配置.eslintrc.js

root: true,
parserOptions: {
parser: 'babel-eslint'
},
env: {
browser: true,
},
extends: [
'plugin:vue/essential',
'standard'
],
plugins: [
'vue'
],
// 在这添加用户自定义的规则
rules: {
'generator-star-spacing': 'off',//强制 generator 函数中 * 号周围使用一致的空格
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',//禁用 debugger
'no-async-promise-executor': 'off',//禁止使用异步函数作为 Promise executor
'no-misleading-character-class': 'off',//不允许在字符类语法中出现由多个代码点组成的字符
'spaced-comment': 'off',//强制在注释中 // 或 /* 使用一致的空格
'semi': 'off',//去掉分号
'no-useless-catch': 'off',//禁止不必要的 catch 子句
'quotes': 'off', //引号类型 `` "" ''
'quote-props': 'off',//对象字面量中的属性名是否强制双引号
'indent': [2, "tab"],//缩进,空格
'prefer-const': 'off',//建议使用const
'space-before-function-paren': [2, {'anonymous': 'never', 'named': 'never', 'asyncArrow': 'always'}],
'space-in-parens': [2, 'always', { "exceptions": ["[]"] } ],
'no-tabs': 'off',
'handle-callback-err': 'off',
'no-unused-vars': 'off',
'eqeqeq': 'off',
'no-undef': 'off',
'brace-style': 'off',
'camelcase': 'off',
'one-var': 'off',
'vue/no-use-v-if-with-v-for': 'off',
'no-useless-escape': 'off',
'no-prototype-builtins': 'off',
'no-return-assign': 'off',
'no-sequences': 'off',
'no-mixed-spaces-and-tabs': [2, 'smart-tabs'],
'standard/no-callback-literal': 'off',
'no-unmodified-loop-condition': 'off',
'vue/no-parsing-error': 'off',
'no-inner-declarations': 'off',
'no-void': 'off',
}

4.配置 eslint-loader, 只检测 src 的业务代码 在dev环境去做eslint检测, 生产环境给去掉了,为了打包时间更短

{
test: /\.(js|vue)$/,
loader: 'eslint-loader',
enforce: 'pre',
include: [resolve('src')],
options: {
formatter: require('eslint-friendly-formatter'),
emitWarning: true
}
}

5.添加.eslintignore文件,忽略掉不检测的文件

/build/
/config/
/dist/
/*.js
/static/
/node_modules/

6.执行lint检测

"lint": "eslint --ext .js,.vue src"

7.现在配置已经做好了,这个时候发现错误一堆,为了不手动改代码,安装 VSCode的插件 ESlint, 我安装的是 2.2.1 版本,2版本 之前和之后的配置版本有些地方不一样,

2以上版本配置默认带vue检测,参考 eslint.bootcss.com/docs/rules/

安装好之后配置 ESlintde 配置


2以上版本添加如下配置,主要是保存时候自动格式化



然后 就可以欢快的去检查每一个文件代码风格问题,打开保存就可以格式化了,有个缺陷就是不能一起格式化,必须得一个文件一个文件去做,可能对已经有的项目有些工作量,

去掉或者自己配置想要的风格方案会更好些