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

TypeScript项目ESLint解析错误及Jest识别问题求助

解决TypeScript ESLint解析错误及Jest全局变量未识别问题

初始解析错误问题

遇到ESLint解析TypeScript类型断言时出错:

Line 11:85:  Parsing error: Unexpected token, expected ","

> 11 | const tracker = new LoggerTracker({ analyticsId: process.env.REACT_APP_ANALYTICS_ID as string});
     |                                                                                     ^

原因:ESLint默认解析器不支持TypeScript的as类型断言语法,需要指定TypeScript专用的ESLint解析器。

第一次修复步骤

  1. 在ESLint配置中添加TypeScript解析器:
module.exports = {
  // ...其他配置
  "parser": "@typescript-eslint/parser",
  // ...
}
  1. 添加后出现Parsing error: ImportDeclaration should appear when the mode is ES6 and in the module context错误,通过配置parserOptions解决:
module.exports = {
  // ...其他配置
  "parserOptions": {
    "ecmaFeatures": {
      "jsx": true
    },
    "sourceType": "module"
  },
  // ...
}

当前问题:Jest全局变量未识别

目前出现describe is not defined等错误,尝试添加env.jest: true和plugin:jest-react/recommended后仍有疑问,以下是适配当前依赖版本的解决方案:

方案1:使用eslint-plugin-jest(适配当前版本)

当前依赖中@typescript-eslint/parser为2.34.0,对应ESLint版本为6.x(react-scripts@3.2.0内置ESLint 6.6.0),因此需要安装适配ESLint 6.x的eslint-plugin-jest版本(推荐23.x系列,如23.20.0):

npm install eslint-plugin-jest@23.20.0 --save-dev

然后修改ESLint配置:

module.exports = {
  "extends": [
    "react",
    "plugin:import/typescript",
    "plugin:jest/recommended" // 替换plugin:jest-react/recommended
  ],
  "env": {
    "browser": true,
    "node": true,
    "jest": true // 保留此项
  },
  // ...其他配置
}

方案2:复用react-scripts内置ESLint配置

react-scripts@3.2.0自带的ESLint配置已包含Jest环境支持,可直接修改extends:

module.exports = {
  "extends": [
    "react-app", // 替换原有的"react"配置
    "plugin:import/typescript"
  ],
  // ...其他配置
}

此方案无需额外安装插件,react-scripts会自动处理Jest全局变量的识别。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 09:05:37