在# ESLint + Prettier提高代码质量(一):基本概念中介绍了ESLint和Prettier的基本用法、主要配置以及和VScode的集成,另外还对如何配置husky + lint-staged,以便在提交代码前运行ESLint进行了说明。本文是第二篇,会对如何在使用了Vue和React的项目中集成ESLint和React进行介绍。
Vue
我自己创建的Vue项目是采用了Vite + Vue3 + Typescript。在配置ESLint的时候会额外有些和Typescript相关的配置,其他都和别的没使用TS的Vue项目一样。
EditorConfig
首先介绍一下编辑器的一些配置,例如缩进等,可以手动在你熟悉的编辑器中进行配置,也可以借助工具EditorConfig。它能通过一个配置文件,让使用了不同IDE的团队成员的编辑器风格一致。如果使用了VSCode,可在插件市场中搜索安装该插件。然后在项目根目录下创建.editorconfig
文件:
# 表示是最顶层的 EditorConfig 配置文件
root = true
[*] # 表示所有文件适用
charset = utf-8 # 设置文件字符集为 utf-8
indent_style = space # 缩进风格(tab | space)
indent_size = 2 # 缩进大小
end_of_line = lf # 控制换行类型(lf | cr | crlf)
trim_trailing_whitespace = true # 去除行首的任意空白字符
insert_final_newline = true # 始终在文件末尾插入一个新行
[*.md] # 表示仅 md 文件适用以下规则
max_line_length = off
trim_trailing_whitespace = false
复制代码
ESLint
安装依赖:
npm i eslint -D
复制代码
执行npx eslint --init
,会在命令行窗口中有一系列问答,例如支持的语言(JS/TS)、框架(Vue/React)、运行环境(Browser/Node)、推荐的shared configuration(例如eslint-config-airbnb-base)等,最终会安装对应的一些依赖:
"eslint-config-airbnb-base",
"eslint-plugin-import",
"eslint-plugin-vue",
"@typescript-eslint/eslint-plugin",
"@typescript-eslint/parser"
复制代码
此外项目根目录下会自动创建好.eslintrc.js
文件:
module.exports = {
env: {
browser: true,
es2021: true,
node: true
},
extends: ['plugin:vue/essential', 'airbnb-base'],
parserOptions: {
ecmaVersion: 12,
parser: '@typescript-eslint/parser',
sourceType: 'module'
},
plugins: ['vue', '@typescript-eslint'],
rules: {}
}
复制代码
补充:关于airbnb风格。
VScode市场中安装ESLint插件。在settions.json
中配置:
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
}
复制代码
关于husky和lint-staged的使用请参阅# ESLint + Prettier提高代码质量(一):基本概念的相关部分。
Prettier
Prettier部分、以及Prettier和ESLint的集成,与# ESLint + Prettier提高代码质量(一):基本概念中相关部分一样的,在此不再赘述,别忘了'plugin:prettier/recommended'
要作为最后一项添加到.eslintrc.js
的extends
数组中。
配置文件总览
我这边几个主要的配置文件如下:
- .eslintrc.js
module.exports = {
env: {
browser: true,
es2021: true,
node: true
},
extends: ['plugin:vue/essential', 'airbnb-base', 'plugin:prettier/recommended'],
parserOptions: {
ecmaVersion: 12,
parser: '@typescript-eslint/parser',
sourceType: 'module'
},
plugins: ['vue', '@typescript-eslint'],
rules: {
'import/no-extraneous-dependencies': ['error', { devDependencies: true }],
'import/extensions': [
'error',
'ignorePackages',
{
js: 'never',
jsx: 'never',
ts: 'never',
tsx: 'never'
}
],
'no-console': 'off',
'import/no-unresolved': 'off',
'no-plusplus': 'off',
'no-param-reassign': ['error', { props: false }]
},
settings: {
'import/resolver': {
node: {
extensions: ['.js', '.jsx', '.ts', '.tsx']
}
}
}
}
复制代码
- .prettierrc
{
"useTabs": false,
"tabWidth": 2,
"printWidth": 100,
"singleQuote": true,
"trailingComma": "none",
"bracketSpacing": true,
"semi": false
}
复制代码
- .vscode/settings.json
{
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
}
}
复制代码
React
我创建的项目是用Creaet React App(简称CRA)创建的Typescript项目。CRA其实自己安装好了ESLint和一些config,但是呢又没有对Typescript的配置,你得自己加,反正我在倒腾的过程中遇到好多问题,网上文章也一堆,各种各样的,估计是因为版本问题,反正我照着弄了是没有成功的。后来终于倒腾好了。
ESLint
为了知道CRA预先装了哪些和lint相关的包,我先创建了一个测试项目,给eject
出来了,然后看到装了以下依赖:
"eslint": "^7.11.0",
"eslint-config-react-app": "^6.0.0",
"eslint-plugin-flowtype": "^5.2.0",
"eslint-plugin-import": "^2.22.1",
"eslint-plugin-jest": "^24.1.0",
"eslint-plugin-jsx-a11y": "^6.3.1",
"eslint-plugin-react": "^7.21.5",
"eslint-plugin-react-hooks": "^4.2.0",
"eslint-plugin-testing-library": "^3.9.2",
"eslint-webpack-plugin": "^2.5.2",
复制代码
可见create react app已经预先安装了ESLint了,所以无需额外再安装。此外,脚手架还预先安装了一个shareable eslint config 叫做eslint-config-react-app,其中包含了一些基本的规则。
如果用CRA创建模板的时候选的Typescript,还需要安装如下的依赖以支持TS:
- @typescript-eslint/eslint-plugin
- @typescript-eslint/parser
- eslint-config-airbnb-typescript
- eslint-config-airbnb
之后删除package.json
中eslintConfig
部分。在项目根目录下创建.eslintrc.js
文件:
module.exports = {
"root": true,
"env": {
"browser": true,
"commonjs": true,
"es6": true,
"jest": true
},
"extends": [
"react-app", // create react app已集成
"react-app/jest", // create react app已集成
"eslint:recommended", // create react app已安装,使用eslint中recommened的规则
"plugin:react/recommended", // create react app已安装, recommended react linting configs
"plugin:@typescript-eslint/recommended", // 需额外手动安装 @typescript-eslint/eslint-plugin
"plugin:react-hooks/recommended", // create react app已安装, hooks相关的lint config
"plugin:prettier/recommended" // 安装好Prettier再添加,可先删除
],
"plugins": ["react", "@typescript-eslint"],
"parser": "@typescript-eslint/parser", // 需手动安装 @typescript-eslint/parser,This allows Eslint to understand TypeScript syntax
"parserOptions": {
"ecmaVersion": 11,
"ecmaFeatures": {
"jsx": true // Allows for the parsing of JSX
},
"sourceType": "module", // Allows for the use of imports
"project": "./tsconfig.json"
},
"settings": {
"react": {
"pragma": "React",
"version": "detect" // Tells eslint-plugin-react to automatically detect the version of React to use
}
},
"rules": {
"no-debugger": "off",
"no-console": "off",
"import/first": "error",
"react/prop-types": "off"
}
}
复制代码
Prettier
Prettier部分、以及Prettier和ESLint的集成,与# ESLint + Prettier提高代码质量(一):基本概念中相关部分一样的,在此不再赘述,别忘了'plugin:prettier/recommended'
要作为最后一项添加到.eslintrc.js
的extends
数组中。
如果遇到报错,可能是CRA中预先安装的ESLint版本低,与Prettier中有不兼容,具体报的什么错我忘了记录了,如果你们遇到报错,可粘贴报错信息,通过科学上网方式搜一下,就能搜到解决办法,即升级eslint的版本:
yarn upgrade eslint
复制代码
配置文件总览
.eslintrc.js
上面已经给出,.prettierrc
可参考vue。
- .vscode/setting.json
{
"editor.defaultFormatter": "esbenp.prettier-vscode",
"eslint.options": {
"configFile": ".eslintrc.js"
},
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
}
}
复制代码
有时候vscode在保存的时候format没有生效,可以重启试试。
后面有时间我把配好的Vue和React项目传到git上。应该会再写两篇关于这两个项目工程化的文章。现在还没有整理好。
欢迎大家留言讨论指出问题。
参考
- Advanced linting with Create React App, Typescript, and ESLint
- 强烈推荐:How to setup eslint for react typescript projects
- 强烈推荐:eslint-config-react-app Recommended way of config integration with ESLint, TypeScript, Prettier and VS Code
- How to add a custom ESLint configuration to a Create React App project
- create-react-app-typescript使用eslint和prettier实现自动格式代码