You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React TypeScript项目ESLint报Parsing error: Unexpected token !的解决方法

解决"Parsing error: Unexpected token !"错误

问题根源

你代码里的!是TypeScript的非空断言操作符,但当前ESLint配置使用的babel-eslint解析器不支持TypeScript语法,这直接导致了解析错误。

修复步骤

  1. 替换解析器依赖
    先卸载无用的babel-eslint:

    npm uninstall babel-eslint
    

    安装TypeScript专属的ESLint解析器:

    npm install @typescript-eslint/parser --save-dev
    
  2. 更新eslintrc.js配置
    将解析器替换为@typescript-eslint/parser,并完善TypeScript文件的规则配置:

    module.exports = {
      env: {
        browser: true,
        es2021: true
      },
      extends: [
        'plugin:react/recommended',
        'plugin:@typescript-eslint/recommended', // 启用TypeScript推荐规则
        'prettier'
      ],
      overrides: [
        {
          files: ['*.ts', '*.tsx'],
          parser: '@typescript-eslint/parser', // 为TS文件指定正确解析器
          parserOptions: {
            project: ['./tsconfig.json']
          },
          plugins: ['@typescript-eslint']
        }
      ],
      parserOptions: {
        ecmaFeatures: {
          jsx: true
        },
        ecmaVersion: 'latest',
        sourceType: 'module'
      },
      plugins: ['react', '@typescript-eslint', 'prettier', 'simple-import-sort'],
    };
    
  3. 校验tsconfig.json配置
    确保你的tsconfig.json包含基础TypeScript配置,示例如下:

    {
      "compilerOptions": {
        "target": "ES2020",
        "module": "ESNext",
        "jsx": "react-jsx",
        "strict": true,
        "moduleResolution": "node",
        "esModuleInterop": true
      },
      "include": ["src/**/*"]
    }
    
  4. 重启ESLint服务
    修改配置后,重启编辑器或ESLint服务,让新配置生效。

补充说明

  • @typescript-eslint/parser是专为TypeScript打造的ESLint解析器,能完整识别TypeScript的所有语法特性(包括非空断言、可选链等)。
  • 加入plugin:@typescript-eslint/recommended可启用TypeScript相关的ESLint规则,进一步规范代码质量。

内容的提问来源于stack exchange,提问作者DamnGood

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 20:30:29