在TypeScript模板的原生Create React App中安装ESLint失败
解决Create React App TypeScript项目中ESLint依赖冲突问题
问题原因
通过npx create-react-app <项目名> --template typescript创建的项目,其依赖的react-scripts@5.0.1自带eslint-config-react-app@7.0.1,该配置依赖@typescript-eslint/eslint-plugin@5.x版本。直接执行npm install --save-dev @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint时,npm会默认拉取最新的@typescript-eslint 6.x版本,而6.x版本要求@typescript-eslint/parser必须匹配6.x,与现有项目中的5.x插件版本冲突,从而触发ERESOLVE错误。
解决方案
方案1:安装匹配版本的依赖
安装与现有项目兼容的5.x版本@typescript-eslint工具链,执行以下命令:
npm install --save-dev @typescript-eslint/parser@5.x @typescript-eslint/eslint-plugin@5.x eslint
方案2:跳过peer依赖检查
使用--legacy-peer-deps参数跳过npm的peer依赖校验,强制安装最新版本(注意:可能存在潜在兼容性风险,需自行验证):
npm install --save-dev @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint --legacy-peer-deps
方案3:复用Create React App内置ESLint配置
实际上Create React App已经内置了ESLint支持,若无需自定义额外规则,可直接使用内置配置,无需手动安装上述依赖。只需在项目中添加ESLint配置文件(如.eslintrc.json),继承内置配置即可:
{ "extends": "react-app" }
验证安装
安装完成后,执行以下命令确认ESLint正常工作:
npx eslint src --ext .ts,.tsx
内容的提问来源于stack exchange,提问作者Joe Crivello
相关产品推荐
相关产品推荐

