使用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
相关产品推荐
相关产品推荐

