使用ts-jest测试导入ESM文件时出现ReferenceError: exports未定义
解决ts-jest导入ESM文件时
ReferenceError: exports is not defined的问题 问题场景
Windows 11环境下,使用jest 29.4.2 + node 18.13.0 + ts-jest运行TypeScript测试:
- 不导入项目内文件时测试正常
- 导入TypeScript编译后的ESM格式JS文件,或导入
node:os这类内置模块时,触发ReferenceError: exports is not defined错误 - 编译后的JS文件无
exports关键字,移除导入扩展名也无法解决
解决方案
1. 统一项目ESM配置
- 项目根目录
package.json必须添加"type": "module",让Node默认将.js文件识别为ESM格式:{ "type": "module" } - 测试目录的
tsconfig.json需明确ESM编译配置:{ "compilerOptions": { "module": "ESNext", "moduleResolution": "NodeNext", "target": "ES2020", "esModuleInterop": false, "skipLibCheck": true }, "include": ["**/*.test.ts"] }
2. 调整jest.config.json的ESM相关配置
补充ESM支持的关键配置项,确保jest与ts-jest的ESM模式对齐:
{ "rootDir": "..", "testEnvironment": "node", "verbose": true, "testMatch": ["**/tests/*.test.ts"], "moduleFileExtensions": ["ts", "js"], "extensionsToTreatAsEsm": [".ts", ".js"], // 新增对ESM格式.js文件的识别 "transformIgnorePatterns": ["!../common/", "!../server/", "!./"], "transform": { "\\.ts$": ["ts-jest", { "tsconfig": "tests/tsconfig.json", "useESM": true, // 显式开启ts-jest的ESM转换模式 "diagnostics": {"ignore": [1343]} }] }, "moduleNameMapper": { "^(\\.{1,2}/.*)\\.js$": "$1" // 处理ESM导入的扩展名要求,避免jest解析冲突 }, "testEnvironmentOptions": { "customExportConditions": ["node", "module"] } }
3. 修正测试脚本参数格式
Windows环境下需确保NODE_OPTIONS参数传递正确,调整package.json的测试脚本:
"test": "cross-env NODE_OPTIONS=\"--experimental-vm-modules\" npx jest --config config/jest.config.json --runInBand"
4. 验证编译产物的纯ESM格式
检查编译ServerConfiguration.js的tsconfig,确保输出为纯ESM:
{ "compilerOptions": { "module": "ESNext", "moduleResolution": "NodeNext", "outDir": "./server", "target": "ES2020", "declaration": true, "esModuleInterop": false }, "include": ["src/server/**/*.ts"] }
编译后的JS文件应使用export class Configuration {...}这类ESM导出语法,而非module.exports。
5. 升级Node版本
Node 18的ESM支持存在部分边缘兼容性问题,升级到Node 19+(推荐20 LTS版本)可提升--experimental-vm-modules的稳定性,大概率解决内置模块导入的报错问题。
额外排查方向
- 若问题仍存在,可暂时移除
transformIgnorePatterns中对server/common目录的排除,让ts-jest强制转换这些目录下的JS文件 - 检查是否存在babel等其他工具干扰模块格式,确保jest是唯一的测试转换工具
内容的提问来源于stack exchange,提问作者SiliconValley
相关产品推荐
相关产品推荐

