【笔记】ESLint学习笔记

前言

ESLint用于检查JavaScript代码是否符合规则,由Nicholas C. Zakas在2013年建立。(维基百科

下载依赖

1
npm install -D eslint 

交互式创建配置文件

1
npx eslint --init

手动创建配置文件

使用内置JS配置

下载依赖

1
npm install -D @eslint/js

修改配置文件

规则等级

off0:关闭规则
warn1:警告
error2:报错

no-unused-vars:禁止未使用的变量
no-console:禁止控制台输出
indent:指定缩进方式
quotes:指定引号类型

single:单引号
double:双引号

eslint.config.js
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
import js from "@eslint/js";

export default [
// 全局忽略文件
{
ignores: [
"node_modules/**",
"dist/**",
"build/**"
]
},

// 定义内置规则
js.configs.recommended,

// 自定义规则
{
files: ["**/*.js"],
languageOptions: {
ecmaVersion: "latest",
sourceType: "module",
globals: {
window: "readonly",
console: "readonly"
}
},
rules: {
"no-unused-vars": "warn",
"no-console": "warn",
"indent": ["error", 2],
"quotes": ["error", "double"]
}
}
];

使用Prettier配置

下载依赖

1
npm install -D @eslint/js prettier eslint-config-prettier eslint-plugin-prettier

修改配置文件

eslint.config.js
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
import js from "@eslint/js";
import eslintConfigPrettier from "eslint-config-prettier";
import eslintPluginPrettier from "eslint-plugin-prettier";

export default [
// 全局忽略文件
{
ignores: [
"node_modules/**",
"dist/**",
"build/**"
]
},

// 定义内置规则
js.configs.recommended,

// 阻止Prettier冲突,以ESLint为准
eslintConfigPrettier,

// 同步Prettier规则
{
files: ["**/*.js"],
languageOptions: {
ecmaVersion: "latest",
sourceType: "module",
globals: {
window: "readonly",
console: "readonly"
}
},
plugins: {
prettier: eslintPluginPrettier
},
rules: {
"prettier/prettier": "error"
}
}
];

检测代码

  • 检测代码,输出错误信息
1
npx eslint <file>.js
1
npx eslint <dir>

检测代码并自动修复代码

1
npx eslint --fix <file>.js
1
npx eslint --fix <dir>

完成

参考文献

哔哩哔哩——许泽鸿