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

如何修复index.tsx Parsing error: Unexpected token, expected ","报错

问题根因

报错触发位置为第9行的as Element语法,这是TypeScript专属的类型断言写法。当前项目的Prettier(搭配eslint-plugin-prettier触发prettier/prettier规则)没有配置TypeScript语法解析能力,默认按纯JavaScript语法解析.tsx文件时,无法识别as关键字的类型断言语义,就会在该位置抛出Unexpected token, expected ","解析错误,和React 18的createRootAPI本身逻辑无关。
代码中冗余导入的ReactDOM、StrictMode不会触发该解析错误,仅属于未使用的无效导入。

修复方案

按以下步骤逐一排查配置即可解决:

  • 安装缺失的TypeScript解析依赖,在项目根目录执行对应包管理工具的安装命令:
# npm 执行
npm install --save-dev prettier @typescript-eslint/parser eslint-plugin-prettier

# yarn 执行
yarn add -D prettier @typescript-eslint/parser eslint-plugin-prettier

# pnpm 执行
pnpm add -D prettier @typescript-eslint/parser eslint-plugin-prettier
  • 更新项目根目录的ESLint配置文件(.eslintrc / .eslintrc.json / .eslintrc.js均可),替换默认解析器为支持TS+TSX的解析器,参考配置如下:
{
  "root": true,
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
    "ecmaVersion": "latest",
    "sourceType": "module",
    "ecmaFeatures": {
      "jsx": true
    }
  },
  "plugins": ["@typescript-eslint", "prettier"],
  "rules": {
    "prettier/prettier": "error"
  }
}
  • 重启ESLint服务/编辑器即可生效。如果重启后仍报错,检查编辑器的Prettier插件是否使用了全局安装的旧版本Prettier,在编辑器设置中将Prettier执行路径指向项目本地的node_modules/prettier目录即可。
  • 临时验证方案:可以把第9行的类型断言临时替换为非as写法,如果报错消失即可确认配置问题:
// 仅做验证用,React+TSX场景不推荐长期使用尖括号类型断言,易和JSX语法冲突
const root = createRoot(<Element>rootElement);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 16:57:23