react-scripts@4.0.3的TS项目安装@typescript-eslint后VS Code lint报错如何解决
问题根源
报错是两个核心原因导致的:
@typescript-eslint相关依赖版本不匹配,且react-scripts@4.0.3内置的eslint 7.x版本和自行安装的依赖存在冲突- VS Code ESLint插件默认可能调用全局eslint,和项目本地依赖版本不一致,且配置文件缺少必要的适配项
解决方案
步骤1:清理并重新安装对齐版本的依赖
- 先删除项目下的node_modules文件夹、package-lock.json文件,清除缓存:
rm -rf node_modules package-lock.json npm cache clean --force
- 安装版本对齐的
@typescript-eslint相关依赖,同时安装适配eslint 7.x的react规则插件:
npm i --save-dev @typescript-eslint/eslint-plugin@4.33.0 eslint-plugin-react@7.26.0
步骤2:调整.eslintrc.js配置
修改配置文件,添加react版本自动检测配置,同时兼容react-scripts内置规则:
module.exports = { env: { browser: true, es2021: true, }, extends: [ 'react-app', // 兼容react-scripts内置的eslint配置 'eslint:recommended', 'plugin:react/recommended', 'plugin:@typescript-eslint/recommended', ], parser: '@typescript-eslint/parser', parserOptions: { ecmaFeatures: { jsx: true, }, ecmaVersion: 12, sourceType: 'module', }, plugins: ['react', '@typescript-eslint'], settings: { react: { version: 'detect' // 自动识别当前安装的react版本,避免eslint-plugin-react报错 } }, rules: {}, };
步骤3:修复VS Code ESLint插件配置
- 打开项目根目录下的
.vscode/settings.json(没有就新建),添加以下配置,指定使用项目本地的eslint:
{ "eslint.useFlatConfig": false, "eslint.nodePath": "./node_modules", "eslint.workingDirectories": ["./"], "eslint.validate": ["javascript", "typescript", "javascriptreact", "typescriptreact"] }
- 按
Ctrl+Shift+P(Mac为Command+Shift+P),选择ESLint: Restart ESLint Server,重启ESLint服务即可。
验证
在项目终端执行本地eslint校验,确认没有报错:
npx eslint ./src --ext .ts,.tsx
如果终端执行正常,VS Code插件也不会再抛出加载错误。
内容的提问来源于stack exchange,提问作者xkeshav
相关产品推荐
相关产品推荐

