react项目如何添加eslint
安装 ESLint 依赖
在 React 项目中安装 ESLint 及其相关插件。推荐使用 eslint-config-react-app,这是 Create React App 的官方配置。运行以下命令:
npm install eslint eslint-plugin-react eslint-plugin-react-hooks eslint-plugin-jsx-a11y @typescript-eslint/parser @typescript-eslint/eslint-plugin --save-dev
如果项目使用 TypeScript,还需安装 TypeScript 相关插件:
npm install @typescript-eslint/parser @typescript-eslint/eslint-plugin --save-dev
初始化 ESLint 配置
在项目根目录运行以下命令生成 ESLint 配置文件:
npx eslint --init
根据提示选择配置选项:
- 选择检查语法和问题
- 选择项目使用的模块类型(通常为 JavaScript modules)
- 选择框架(React)
- 是否使用 TypeScript(根据项目情况选择)
- 选择代码运行环境(Browser)
- 选择配置文件的格式(推荐
.eslintrc.js)
配置 .eslintrc.js
手动调整生成的 .eslintrc.js 文件以适配 React 项目。以下是一个常见配置示例:
module.exports = {
env: {
browser: true,
es2021: true,
},
extends: [
'eslint:recommended',
'plugin:react/recommended',
'plugin:react-hooks/recommended',
'plugin:jsx-a11y/recommended',
],
parserOptions: {
ecmaFeatures: {
jsx: true,
},
ecmaVersion: 12,
sourceType: 'module',
},
plugins: ['react', 'react-hooks', 'jsx-a11y'],
rules: {
'react/react-in-jsx-scope': 'off', // React 17+ 不需要显式导入 React
'react/prop-types': 'off', // TypeScript 项目中可关闭
},
};
如果是 TypeScript 项目,需修改 parser 和 parserOptions:
parser: '@typescript-eslint/parser',
parserOptions: {
project: './tsconfig.json',
},
添加脚本命令
在 package.json 中添加 ESLint 检查命令:
"scripts": {
"lint": "eslint .",
"lint:fix": "eslint . --fix"
}
运行 npm run lint 检查代码,npm run lint:fix 自动修复部分问题。
配置编辑器集成
在 VS Code 中安装 ESLint 扩展,并在设置中启用保存时自动修复:
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
}
忽略文件配置
在项目根目录创建 .eslintignore 文件,添加需要忽略的文件或目录:
node_modules
build
dist
*.config.js
集成 Prettier(可选)
如果需要与 Prettier 配合使用,安装相关插件:
npm install prettier eslint-config-prettier eslint-plugin-prettier --save-dev
在 .eslintrc.js 的 extends 和 plugins 中添加 Prettier:
extends: [
// ...其他配置
'plugin:prettier/recommended',
],
plugins: [
// ...其他插件
'prettier',
],
rules: {
'prettier/prettier': 'error',
},






