在 react/vue 项目中使用 eslint

在 vscode 中使用 eslint

首先下载 vscode 的 eslint 插件

在项目的 .vscode/settings.json 中设置

1
2
3
{
"eslint.autoFixOnSave": true
}

或者在 vscode 中全局设置

管理 -> 设置 -> 搜索 eslint -> 勾选 Eslint: Auto Fix On Save

以 react 项目为例

在 .eslintrc 文件中配置

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
38
39
40
41
42
43
44
45
46
47
48
49
50
{
"root": true,
"env": {
"browser": true,
"node": true,
"es6":true
},
"extends": [
"plugin:prettier/recommended",
"prettier/react",
"plugin:react/recommended"
],
"plugins": [
"react"
],
"rules": {
"no-debugger": "error",
"indent": 0,
"linebreak-style": 0,
"quotes": 0,
"arrow-spacing": ["error", { "before": true, "after": true }],
"semi": ["error", "never"],
"comma-spacing": ["error", { "before": false, "after": true }],
"no-console": "off",
"no-reserved-keys": "off",
"no-unused-vars": ["error", { "vars": "all", "args": "none" }],
"prettier/prettier": [
"error",
{
"semi": false,
"singleQuote": true,
"bracketSpacing": true,
"jsxBracketSameLine": true,
"trailingComma": "es5",
"jsxSingleQuote": false,
"parser": "flow",
"endOfLine":"auto",
"printWidth": 200
}
]
},
"parser": "babel-eslint",
"parserOptions": {
"ecmaVersion": 6,
"ecmaFeatures": {
"jsx": true
},
"sourceType": "module"
}
}

在 package.json 的添加 eslint 命令

1
2
3
4
5
6
7
8
{
// ...
"scripts": {
// ...
"eslint": "eslint ./src/**/*.js ./src/**/*.jsx",
"eslint:fix": "eslint ./src/**/*.js ./src/**/*.jsx --fix",
}
}

执行命令 npm run eslint 检测 eslint 语法是否报错
执行命令 npm run eslint:fix 修复 eslint 报错的语法

使用 husky 在 git commit/push 前检测 eslint

在 package.json 的添加 husky 配置

1
2
3
4
5
6
7
8
9
{
// ...
"husky": {
"hooks": {
"pre-commit": "npm run eslint",
"pre-push": "npm run eslint"
}
}
}

附上一份 vue 项目的 eslint 配置

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
38
39
40
41
42
module.exports = {
root: true,
env: {
node: true
},
'extends': [
'plugin:vue/recommended',
// '@vue/prettier'
],
rules: {
'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off',
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
"indent": 0,
"linebreak-style": 0,
"quotes": 0,
"arrow-spacing": ["error", { "before": true, "after": true }],
"semi": ["error", "never"],
"comma-spacing": ["error", { "before": false, "after": true }],
"no-console": "off",
"vue/script-indent": [
'error',
2,
{
"baseIndent": 1,
"switchCase": 1
}
],
"vue/order-in-components": "off",
"vue/require-default-prop": "off",
"vue/html-self-closing": "off",
"vue/attribute-hyphenation": "off",
"vue/max-attributes-per-line": ["error", {
"singleline": 3,
"multiline": 1
}],
"vue/attributes-order": "off",
"no-reserved-keys": "off",
},
parserOptions: {
parser: 'babel-eslint'
}
}

我们每一个人都应该是自己生活的主宰,而不是别人手里的行货。
——王小波