DEBUG.WIKI
ZgoCloud:多地区部署,按需选节点;日本、美国、香港、德国
V.PS:让项目靠近用户,亚太、欧洲、北美 KVM VPS
晚安云;香港 CN2 ¥15/月

解决 ESLint 报错 Parsing error: Cannot find module @typescript-eslint/parser

在配置 TypeScript 项目代码静态检查时报错 Parsing error: Cannot find module @typescript-eslint/parser 或版本不兼容。本文详解 ESLint 与解析器依赖版本配比、Monorepo 寻径与配置继承规范。

问题现象

在运行 npm run lint 或保存代码时,编辑器(VS Code)与终端输出以下错误:

/workspace/src/index.ts
  1:1  error  Parsing error: Cannot find module '@typescript-eslint/parser'
Require stack:
- /workspace/node_modules/eslint/lib/cli-engine/formatters/stylish.js

代码校验完全无法启动,所有 TypeScript 文件被标红阻断。

触发根因

  1. 解析器未实际安装:在 .eslintrc.js 中配置了 parser: '@typescript-eslint/parser',但 package.json 中的 devDependencies 遗漏了该包。
  2. ESLint 与 TypeScript-ESLint 大版本脱节:例如使用了较新版本的 ESLint 9.x,而项目中引入的 @typescript-eslint/parser 仍然是 5.x 老版本,API 架构不兼容(ESLint 9 转向 Flat Config 扁平配置体系)。
  3. Monorepo 依赖提升隔离机制:在使用 pnpm 或 yarn workspaces 时,解析器被装在了根目录而非子包,且未在配置中指定根解析器路径。

诊断排查步骤

检查本地 node_modules 中是否存在该包以及版本信息:

npm list @typescript-eslint/parser eslint

若回显为 (empty) 或标红 ERR!,确认是依赖缺失或版本冲突。

解决方案

方案一:完整安装匹配的配套工具包

确保将 parser 与 plugin 一同作为开发依赖安装:

# npm 安装
npm install --save-dev eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin typescript

# pnpm 安装
pnpm add -D eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin typescript

方案二:核验 .eslintrc.js 配置结构

确保解析器与插件名称语法无误:

// .eslintrc.js (传统配置格式 ESLint <= 8)
module.exports = {
  root: true,
  parser: '@typescript-eslint/parser',
  parserOptions: {
    ecmaVersion: 'latest',
    sourceType: 'module',
    project: './tsconfig.json' // 若开启了类型感知规则
  },
  plugins: ['@typescript-eslint'],
  extends: [
    'eslint:recommended',
    'plugin:@typescript-eslint/recommended'
  ]
};

方案三:若升级至 ESLint 9+ 采用 Flat Config 配置

如果使用的是 ESLint 9+,配置需改为 eslint.config.js(或 eslint.config.mjs):

// eslint.config.mjs
import tsParser from '@typescript-eslint/parser';
import tsPlugin from '@typescript-eslint/eslint-plugin';

export default [
  {
    files: ['**/*.ts', '**/*.tsx'],
    languageOptions: {
      parser: tsParser,
      parserOptions: {
        sourceType: 'module'
      }
    },
    plugins: {
      '@typescript-eslint': tsPlugin
    },
    rules: {
      ...tsPlugin.configs.recommended.rules
    }
  }
];

验证方法

执行全量代码检查:

npx eslint src/ --ext .ts,.tsx

命令正常解析代码并输出语法规范结果,不再抛出解析器模块缺失异常,修复完成。