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

使用ES Modules+TS结合Jest测试时遇import语句报错问题

解决Jest在ES模块TypeScript项目中"cannot use import statement outside module"报错问题

在Express+TypeScript项目中使用Jest测试,且采用ES模块的import/export语法替代CommonJS的require时,出现cannot use import statement outside module错误,可通过以下配置调整解决:

1. 创建Jest配置文件

在项目根目录新建jest.config.ts,配置ts-jest对ES模块的支持:

/** @type {import('ts-jest').JestConfigWithTsJest} */
export default {
  preset: 'ts-jest/presets/default-esm',
  testEnvironment: 'node',
  moduleNameMapper: {
    '^(\\.{1,2}/.*)\\.js$': '$1',
  },
  extensionsToTreatAsEsm: ['.ts'],
  transform: {
    '^.+\\.tsx?$': ['ts-jest', {
      useESM: true,
    }],
  },
};

2. 修改package.json的测试脚本

更新scripts中的test命令,添加Node.js ES模块支持的参数:

"scripts": {
  "test": "NODE_OPTIONS=--experimental-vm-modules jest",
  "start": "node src/index.ts",
  "dev": "nodemon src/index.ts",
  "build": "tsc"
}

3. 调整tsconfig.json配置

确保TypeScript配置正确识别ES模块及测试文件:

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "sourceMap": true,
    "resolveJsonModule": true,
    "outDir": "dist",
    "esModuleInterop": true,
    "allowJs": true
  },
  "include": ["src/**/*", "__tests__/**/*"],
  "files": ["types.d.ts"],
  "ts-node": {
    "esm": true,
    "compiler": "typescript"
  }
}

关键配置说明

  • ts-jest/presets/default-esm预设:让ts-jest默认适配ES模块语法
  • extensionsToTreatAsEsm:指定.ts文件作为ES模块处理
  • moduleNameMapper:解决TypeScript编译后导入路径带.js后缀的问题,测试时直接映射到原.ts文件
  • NODE_OPTIONS=--experimental-vm-modules:启用Node.js的ES模块虚拟机支持,确保Jest能正确解析import语句

内容的提问来源于stack exchange,提问作者Gábor Adorjáni

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 16:34:52