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

Jest引入ESM格式内部依赖时出现Unexpected token 'export'错误求助

解决Jest测试ESM monorepo包时的Unexpected token 'export'错误

以下是无需调整@repo/db-client包构建方式的解决方案,按优先级尝试:

1. 强制启用Jest的ESM实验性支持

在运行Jest时添加Node.js的ESM实验参数,这是解决ESM兼容问题最直接的手段:
在项目package.json的测试脚本中修改:

"scripts": {
  "test": "NODE_OPTIONS=--experimental-vm-modules jest"
}

2. 修正Jest配置文件的ESM适配项

将jest.config.js改为jest.config.mjs(确保配置文件本身是ESM格式),并添加以下核心配置:

export default {
  // 明确将TS文件视为ESM
  extensionsToTreatAsEsm: ['.ts'],
  // 支持的文件扩展名
  moduleFileExtensions: ['ts', 'mjs', 'js', 'json'],
  // 禁用默认转译(ESM无需转译为CJS)
  transform: {},
  // 处理TS编译后导入路径带.js的问题
  moduleNameMapper: {
    '^(\\.{1,2}/.*)\\.js$': '$1',
    // 映射monorepo包路径,确保Jest能正确解析
    '@repo/db-client/(.*)': '<rootDir>/../path-to-db-client/src/$1',
    '@repo/db-client': '<rootDir>/../path-to-db-client/src/index.ts'
  },
  // 不对monorepo内部包进行转译忽略
  transformIgnorePatterns: [
    'node_modules/(?!@repo/db-client)'
  ],
  testEnvironment: 'node'
};

注意:path-to-db-client需要替换为你monorepo中@repo/db-client包的实际相对路径。

3. 确保包的ESM标识正确传递

  • 确认@repo/db-client的package.json中"type": "module"字段存在且位于根目录
  • 后端项目的package.json同样必须包含"type": "module"
  • 如果测试文件是.js后缀,可改为.mjs后缀,避免Node.js默认按CJS解析

4. 适配TS-Jest的ESM模式(如果用TS-Jest转译)

如果你的项目依赖ts-jest处理TS文件,需在transform配置中启用ESM支持:

export default {
  // ...其他配置
  transform: {
    '^.+\\.tsx?$': ['ts-jest', { useESM: true }]
  }
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 15:12:13