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

Jest+ts-jest环境下TypeScript默认导入失效问题求助

问题修复:Jest + ts-jest 默认导入第三方库失败

问题根源

你当前tsconfig.json设置了module: Node16,启用了Node.js 16+的严格模块解析规则。dotenv属于CommonJS模块,虽然allowSyntheticDefaultImports: true让TypeScript编译时允许默认导入语法,但该选项仅做语法层面放行,不会生成运行时兼容CommonJS模块的代码;同时ts-jest的默认配置未匹配Node16模块模式的互操作要求,导致测试运行时无法识别默认导出。

修复步骤

1. 更新 tsconfig.json

在compilerOptions中添加esModuleInterop: true,该选项会生成辅助代码,让ES模块能正确导入CommonJS模块的默认导出:

{
  "compilerOptions": {
    // ... 原有配置
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true, // 新增配置
    // ... 原有配置
  }
}

2. 调整 jest.config.js

修改transform中的ts-jest配置,开启ESM支持并同步ES模块互操作设置,确保测试运行时的模块解析与TS编译逻辑一致:

module.exports = {
  transform: { 
    '^.+\\.ts?$': ['ts-jest', {
      useESM: true,
      esModuleInterop: true
    }]
  },
  testEnvironment: 'node',
  testRegex: '/tests/.*\\.(test|spec)?\\.(ts|tsx)$',
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
  moduleNameMapper: {
    '^@apps/(.*)$': '<rootDir>/src/apps/$1',
    '^@core/(.*)$': '<rootDir>/src/core/$1',
  },
};

验证

修改完成后重新运行测试,import dotenv from 'dotenv';即可正常工作,无需调整代码导入风格。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 01:07:36