
在项目中使用 ESLint 和 Prettier(以 React + TypeScript 为例)
使用 CRA 初始化项目
sh
npx create-react-app my-app --template typescript
# or
yarn create react-app my-app --template typescript使用 ESLint
安装依赖
CRA 自带了
eslint,不用额外安装
sh
yarn add -D @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint-plugin-reacteslint:javascript代码检测工具@typescript-eslint/parser:ESLint的解析器,用于解析typescript@typescript-eslint/eslint-plugin:ESLint插件,内置了typescript代码的相关规范eslint-plugin-react:ESLint插件,内置了react代码的相关规范
配置文件 .eslintrc.js 介绍
根目录新建 .eslintrc.js 文件
js
module.exports = {
// 运行环境
env: {
browser: true,
es2020: true
},
// 继承的规则 / 插件
extends: ['plugin:react/recommended', 'plugin:@typescript-eslint/recommended'],
// 解析器
parser: '@typescript-eslint/parser',
// 解析器配置
parserOptions: {
ecmaFeatures: {
jsx: true
},
ecmaVersion: 2018,
sourceType: 'module'
},
// 插件
plugins: ['react', '@typescript-eslint'],
settings: {
// 自动检测 React 的版本
react: {
version: 'detect'
}
},
// 规则
rules: {
'react/prop-types': 0,
'react/forbid-prop-types': 0,
'react/jsx-indent': 0
}
}添加脚本命令
在 package.json 的 scripts 配置项中写入 "lint": "eslint --ext js,ts,tsx src"
使用 Prettier
Prettier 是一个代码格式化工具,它通过解析代码并使用自己的规则(考虑最大行长)重新格式化代码,从而实现一致的编码风格
安装
sh
yarn add -D prettier eslint-config-prettier eslint-plugin-prettierprettier代码格式化程序eslint-config-prettier: 关闭ESLint中不必要的或可能与Prettier冲突的规则。eslint-plugin-prettier: 将Prettier作为ESLint规则运行,并将差异报告为单个ESLint问题。
修改 .eslintrc.js
eslint-config-prettier 8.0.0 之后版本
在 extends 配置项中增加 prettier 和 plugin:prettier/recommended
eslint-config-prettier 8.0.0 之前版本
在 extends 配置项中增加 prettier/@typescript-eslint 和 plugin:prettier/recommended
自定义 Prettier 风格规则
在根目录创建 .prettierrc 文件和 .prettierignore
.prettierrc
- 自定义
Prettier风格规则
json
{
"singleQuote": true,
"semi": false,
"trailingComma": "none",
"printWidth": 80,
"overrides": [
{
"files": ".prettierrc",
"options": { "parser": "json" }
}
]
}.prettierignore
配置 Prettier 忽略文件
sh
package.json
tsconfig.json添加脚本命令
在 package.json 的 scripts 配置项中写入 "fix": "prettier --write ./src"

