0%

JS的Eslint配置笔记

自己如果新建一个项目了,配置一个 eslint 是有必要的。

安装 Eslint

全局安装 Eslint

1
npm install -g eslint

在项目中安装 eslint

1
npm install eslint

然后自己按提示按需手动配置,我的如下,因为我只需要写 nodejs 方面的。

1
2
3
npx eslint --init
# or
yarn run eslint --init
1
2
3
4
5
6
7
8
√ How would you like to use ESLint? · style
√ What type of modules does your project use? · commonjs
√ Which framework does your project use? · none
√ Does your project use TypeScript? · No / Yes
√ Where does your code run? · browser
√ How would you like to define a style for your project? · guide
√ Which style guide do you want to follow? · airbnb
√ What format do you want your config file to be in? · JavaScript

这样项目中 Eslint 就配置好了,会自动添加 eslint 的配置文件。

添加 Prettier

使用 Pretteier 配合 Eslint 对代码进行格式化。统一代码风格。

1
npm install -D eslint-config-prettier eslint-plugin-prettier

最后配置一下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
module.exports = {
env: {
browser: true,
commonjs: true,
es2021: true,
},
extends: ['airbnb', 'prettier'],
parserOptions: {
ecmaVersion: 12,
},
plugins: ['prettier'],
rules: {
'prettier/prettier': ['error'],
},
};

vscode 安装插件

配合 vscode 进行代码提示

vscode 需要装 2 个插件,可以右键格式化代码并且在保存的时候自动修复代码

安装好之后,进入 vscode 设置,搜 save 关键词,进行一下设置就可以了

最后贴一下我的 package.json 文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
{
"name": "study-eslint",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"dependencies": {},
"devDependencies": {
"@typescript-eslint/eslint-plugin": "^4.6.0",
"@typescript-eslint/parser": "^4.6.0",
"eslint": "^7.12.1",
"eslint-config-airbnb-base": "^14.2.0",
"eslint-config-prettier": "^6.15.0",
"eslint-config-standard": "^15.0.1",
"eslint-plugin-import": "^2.22.1",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-prettier": "^3.1.4",
"eslint-plugin-promise": "^4.2.1",
"eslint-plugin-standard": "^4.0.2",
"typescript": "^4.0.5"
}
}