React+TypeScript项目ESLint加载@typescript-eslint插件报错求助
解决ESLint加载@typescript-eslint插件时的SyntaxError: Unexpected token '.'问题
问题背景
在React+TypeScript项目中使用ESLint做代码检查,相关依赖版本:
"@typescript-eslint/eslint-plugin": "^6.3.0", "@typescript-eslint/parser": "^6.0.0", "eslint": "^8.45.0",
.eslintrc.cjs配置如下:
/* eslint-env node */ module.exports = { root: true, env: { browser: true, es2020: true }, extends: [ 'eslint:recommended', 'plugin:@typescript-eslint/recommended', 'plugin:@typescript-eslint/recommended-requiring-type-checking', 'plugin:react-hooks/recommended', ], parser: '@typescript-eslint/parser', parserOptions: { ecmaVersion: 'latest', sourceType: 'module', project: true, tsconfigRootDir: __dirname, }, plugins: ['react-refresh'], rules: { 'react-refresh/only-export-components': [ 'warn', { allowConstantExport: true }, ], '@typescript-eslint/no-non-null-assertion': 'off', "@typescript-eslint/no-unused-vars": ["error", { "argsIgnorePattern": "^_" }], }, }
WebStorm中所有文件报错:
SyntaxError: Failed to load plugin '@typescript-eslint' declared in '.eslintrc.cjs': Unexpected token '.'
已尝试升级Node至20.5.1、重装依赖、验证配置文件等方法无效,同事使用相同文件无问题。
可能的原因及解决方法
1. 检查WebStorm使用的Node版本
虽然全局Node已升级,但WebStorm可能默认使用内置Node或其他版本:
- 打开WebStorm设置(
File > Settings),进入Languages & Frameworks > Node.js and NPM - 确认
Node interpreter选择的是你升级后的20.5.1版本(若使用nvm等版本管理工具,需指定对应版本路径)
2. 强制WebStorm使用项目本地ESLint
WebStorm可能调用全局ESLint版本与项目依赖不兼容:
- 进入
Settings > Languages & Frameworks > JavaScript > Code Quality Tools > ESLint - 选择
Automatic ESLint configuration,或手动指定ESLint package为项目根目录下的node_modules/eslint
3. 清除WebStorm缓存
缓存可能导致配置未更新:
- 点击
File > Invalidate Caches...,选择Invalidate and Restart,重启后重新加载项目
4. 修复依赖版本冲突
@typescript-eslint的parser与plugin版本尽量保持一致:
- 修改package.json,将
@typescript-eslint/parser版本改为^6.3.0,与plugin版本匹配 - 删除
package-lock.json(或yarn.lock),执行npm install重新安装依赖
5. 验证命令行ESLint是否正常运行
先确认ESLint本身配置无问题:
- 在项目根目录执行命令:
npx eslint .- 若命令行报错:重点排查依赖或tsconfig.json(确保tsconfig.json存在且格式正确)
- 若命令行正常:问题集中在WebStorm集成配置,重复步骤1-3
6. 检查tsconfig.json路径
配置中parserOptions.project: true会自动查找根目录的tsconfig.json:
- 确保项目根目录存在tsconfig.json,且无语法错误
- 若tsconfig不在根目录,需指定具体路径,例如
project: './tsconfig.json'
内容的提问来源于stack exchange,提问作者Karri Aravind
相关产品推荐
相关产品推荐

