ESLint报Plugin "react"在.eslintrc.js与BaseConfig间冲突如何解决

问题描述
完成ESLint配置后执行校验或启动项目时出现报错:
Plugin "react" was conflicted between ".eslintrc.js" and "BaseConfig » /frontend/node_modules/react-scripts/node_modules/eslint-config-react-app/base.js"
当前.eslintrc.js配置内容如下:
module.exports = { env: { browser: true, es2021: true, }, extends: [ 'plugin:react/recommended', 'airbnb', 'airbnb/hooks', 'plugin:@typescript-eslint/recommended', 'plugin:@typescript-eslint/recommended-requiring-type-checking', 'prettier', ], parser: '@typescript-eslint/parser', parserOptions: { ecmaFeatures: { jsx: true, }, ecmaVersion: 'latest', sourceType: 'module', tsconfigRootDir: __dirname, project: ['./tsconfig.json'], }, plugins: [ 'react', '@typescript-eslint', ], ignorePatterns: [ ".eslintrc.js" ], rules: { 'no-use-before-define': "off", "@typescript-eslint/no-use-before-define": "off", 'import/prefer-default-export': "off", 'import/extensions': [ 'error', { js: 'never', jsx: 'never', ts: 'never', tsx: 'never', }, ], 'react/jsx-filename-extension': [ 'error', { extensions: ['.jsx', '.tsx'], }, ], 'react/react-in-jsx-scope': 'off', 'no-void': [ 'error', { allowAsStatement: true, }, ], "react/function-component-definition": [ 2, { "namedComponents": "arrow-function" } ] }, settings: { 'import/resolver': { node: { paths: ['src'], extensions: ['.js', '.jsx', '.ts', '.tsx'] }, }, }, };
复现问题的前置操作:
- 执行
npx create-react-app my-app --template typescript创建TypeScript版React项目 - 执行
yarn run eslint --init初始化ESLint配置 - 执行
yarn add -D @typescript-eslint/eslint-plugin @typescript-eslint/parser安装TypeScript相关ESLint依赖 - 执行
npx install-peerdeps --dev eslint-config-airbnb安装Airbnb ESLint规则依赖
报错原因
Create React App(react-scripts)内置了独立的ESLint基础配置,其中已经默认加载了react相关插件,自定义根目录的.eslintrc.js中重复声明了react插件,两边加载的插件版本、配置逻辑不一致,就会触发冲突报错。
解决方案
两种方案选其一即可修复问题:
方案1:关闭react-scripts内置ESLint校验,完全使用自定义配置
在项目根目录新建.env文件,添加如下配置:
DISABLE_ESLINT_PLUGIN=true
添加完成后重启开发服务、重新执行lint命令即可,react-scripts会跳过内置ESLint规则加载,直接消除冲突。
注意:该方案下所有ESLint校验完全走自定义配置,需要自行保证规则覆盖完整。
方案2:调整自定义配置,避免和内置配置重复加载
修改.eslintrc.js,移除plugins数组中的'react'项,不要重复声明已经被内置配置加载的插件,修改后的plugins配置示例:
plugins: [ '@typescript-eslint', ],
如果调整后仍存在冲突,可在配置最顶部增加root: true声明,强制ESLint以当前配置文件为根配置,停止向上查找合并其他层级的配置:
module.exports = { root: true, // 其余原有配置保持不变 }
内容的提问来源于stack exchange,提问作者TiShow
相关产品推荐
相关产品推荐

