← 中文资源

简体中文版本

ESLint: 合法文件出现 Parsing error

修复 ESLint 的解析错误:对齐 parser 与 parserOptions,加入 TypeScript 或 JSX 插件,并匹配语言版本。

阅读英文原文

症状

一个能编译、能运行的文件却出现 Parsing error: Unexpected token。它常在把含 JSX 或 TypeScript 语法的文件纳入 lint 范围后出现。

诊断

记录报错 token 并打印生效配置:

npx eslint --print-config src/Component.tsx

若对 .tsx 文件使用的仍是默认 espree 解析器,即为不匹配。

修复

配置正确的解析器与选项:

// flat config
import tseslint from 'typescript-eslint';

export default [
  {
    files: ['**/*.ts', '**/*.tsx'],
    languageOptions: {
      parser: tseslint.parser,
      parserOptions: { ecmaVersion: 2022, sourceType: 'module', ecmaFeatures: { jsx: true } },
    },
  },
];

验证

对该文件运行 eslint;它现在报告 lint 结果(或为空)而非解析错误,证明解析器已理解该语法。