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

使用TypeScript时遭遇ReferenceError: Can't find variable: exports错误求助

解决React + TypeScript项目中"ReferenceError: Can't find variable: exports"错误

错误原因

你的tsconfig.json中module被设置为commonjs,但React项目(通常基于webpack、Vite等构建工具)默认采用ES模块规范,浏览器环境不支持CommonJS的exports语法,两者模块规范不匹配导致报错。另外你执行的npx tsc因为noEmit: true的配置,并不会生成实际编译文件,实际运行的是构建工具处理的代码,进一步加剧了规范冲突。

解决方案

1. 修改TypeScript的模块规范配置

打开tsconfig.json,将compilerOptions里的module字段从commonjs改为esnext(或es6):

{
  "compilerOptions": {
    "target": "es6",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext", // 替换原commonjs配置
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": [
    "src"
  ],
  "exclude": [
      "node_modules"
  ]
}

这个修改会让TypeScript生成符合ES模块规范的导出代码,和React项目的构建工具兼容。

2. 移除不必要的npx tsc命令

由于你的tsconfig.json中设置了noEmit: true,TypeScript仅做类型检查,不会输出编译后的文件。React项目的npm start命令会由构建工具(如create-react-app内置的webpack)自动处理TypeScript编译,因此直接运行npm start即可,无需提前执行npx tsc。

3. 保持ES模块语法一致性

确保项目中的所有导入导出都使用ES模块语法(import/export),避免混合使用CommonJS的require/module.exports写法。

内容的提问来源于stack exchange,提问作者O'Niel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 00:40:21