react项目如何添加eslint
安装 ESLint 及相关依赖
在项目根目录下运行以下命令安装 ESLint 及相关插件:
npm install eslint eslint-plugin-react eslint-plugin-react-hooks eslint-plugin-jsx-a11y @typescript-eslint/parser @typescript-eslint/eslint-plugin --save-dev
初始化 ESLint 配置
运行以下命令生成 ESLint 配置文件:
npx eslint --init
根据提示选择 React 和 TypeScript(如适用)相关配置选项。
配置 .eslintrc.js
生成的配置文件示例(可根据需求调整):

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/prop-types': 'off',
'react/react-in-jsx-scope': 'off',
},
};
添加 TypeScript 支持(可选)
若项目使用 TypeScript,需修改配置:
module.exports = {
extends: [
// ...其他配置
'plugin:@typescript-eslint/recommended',
],
parser: '@typescript-eslint/parser',
plugins: [
// ...其他插件
'@typescript-eslint',
],
};
创建忽略文件 .eslintignore
添加需要忽略检查的文件或目录:

node_modules
build
dist
*.config.js
添加 npm 脚本
在 package.json 中添加 lint 命令:
"scripts": {
"lint": "eslint .",
"lint:fix": "eslint . --fix"
}
配置编辑器集成
在 VSCode 中安装 ESLint 扩展,并确保工作区设置启用自动修复:
{
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
}
}
自定义规则配置
根据项目需求调整规则,常见规则示例:
rules: {
'jsx-a11y/anchor-is-valid': ['warn', { aspects: ['invalidHref'] }],
'react-hooks/rules-of-hooks': 'error',
'react-hooks/exhaustive-deps': 'warn',
'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'warn'
}






