eslint进行代码检查

前言

最近项目进行到收尾阶段,公司对于代码质量抓的比较严,后端一般使用sonar进行代码扫描。而JavaScript是弱类型语言,其实很有扫描检查的必要。
sonar支持JStypeScript的扫描,不支持Vue。因此改用eslint进行代码扫描。
平常在开发中,都是嫌麻烦把eslint关掉的。。

安装依赖

除了安装eslint以外,还需安装eslint-plugin-vue插件来检查Vue代码。
直接-g吧。
npm install eslint eslint-plugin-vue -g

配置

一般推荐使用配置文件进行配置,在项目根目录下创建.eslintrc.json,其中写入各个配置项。
如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
{
"root": true,
//此项是用来告诉eslint找当前配置文件不能往父级查找
"extends": ["plugin:vue/essential","eslint:recommended"],
//vue插件和推荐eslint规则
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module",
"ecmaFeatures": {
"jsx": true
}
},
//指定为浏览器环境
"env": {
"es6": true,
"browser": true,
"node": true
},
"rules": {
"camelcase": "error",
"eqeqeq": "error",
"no-console": "error",
"no-alert": "error",
"require-jsdoc": ["error", {
"require": {
"FunctionDeclaration": false,
"MethodDefinition": false,
"ClassDeclaration": false,
"ArrowFunctionExpression": false
}
}],
"new-cap": "error",
"brace-style": "error",
"comma-dangle": "error",
"no-param-reassign": "error"
}
}

注意json中不能有注释,复制下来记得删除注释。

#规则
举几个常用的规则:

1
2
3
4
5
6
7
8
9
10
11
{
"no-alert": 2,//禁止使用alert confirm prompt
"no-console": 2,//禁止使用console
"no-const-assign": 2,//禁止修改const声明的变量
"no-debugger": 2,//禁止使用debugger
"no-dupe-keys": 2,//在创建对象字面量时不允许键重复
"no-dupe-args": 2,//函数参数不能重复
"no-duplicate-case": 2,//switch中的case标签不能重复
"no-empty": 2,//块语句中的内容不能为空
"no-eval": 1,//禁止使用eval
}

具体规则见官网 https://eslint.org/docs/rules/

代码扫描

项目根目录运行eslint --ext .js,.vue src
或者将运行结果输出到文件eslint --ext .js,.vue src > log.txt

分析

通过对输出的文件分析,我们项目的错误(警告)有以下几种

报错 规则 规则
Unexpected trailing comma comma-dangle 对象结尾跟随了一个多余的逗号
Expected ‘===’ and instead saw ‘==’ eqeqeq 必须使用全等
‘util’ is not defined no-undef 不能有声明后未被使用的变量或参数
‘delSpace’ is defined but never used no-unused-vars 不能有声明后未被使用的变量或参数
Elements in iteration expect to have ‘v-bind:key’ directives vue/require-v-for-key v-for中需v-bind:key
Unexpected console statement no-console no-console