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

如何让Jest将jest.config文件(而非spec文件)作为ESM加载?

解决Jest配置文件(jest.config.ts)以ESM模式加载的问题

问题详情

  • 已能正常运行ESM格式的.spec.ts测试文件,但jest.config.ts无法以ESM模式加载——原因是该文件导入了仅支持ESM的模块(如strip-json-comments 4.0及以上版本)。
  • jest.config.ts代码示例:
import strip from 'strip-json-comments' 

export default function config(){
  // 调用ESM函数
  strip(...);
  // 返回Jest配置对象
  return {
    // 你的配置项
  };
}
  • 触发的错误信息:

Error: Jest: Failed to parse the TypeScript config file jest.config.ts
Error [ERR_REQUIRE_ESM]: require() of ES Module node_modules/.pnpm/strip-json-comments@5.0.1/node_modules/strip-json-comments/index.js from jest.config.ts not supported.
Instead change the require of index.js in jest.config.ts to a dynamic import() which is available in all CommonJS modules.

  • 当前已做配置:package.json中添加了"type": "module",运行命令为:
node --loader ts-node/esm --experimental-specifier-resolution=node --experimental-import-meta-resolve --experimental-vm-modules node_modules/jest/bin/jest.js

可行解决方案

方案1:显式指定Jest配置文件的ESM加载方式

Jest默认会用CommonJS逻辑加载配置文件,需通过命令行参数明确引导其使用ESM加载器。调整运行命令为:

NODE_OPTIONS="--loader ts-node/esm --experimental-specifier-resolution=node --experimental-vm-modules" npx jest --config jest.config.ts

也可以把命令写进package.json的scripts里,方便复用:

{
  "scripts": {
    "test": "NODE_OPTIONS=\"--loader ts-node/esm --experimental-specifier-resolution=node --experimental-vm-modules\" jest --config jest.config.ts"
  }
}

方案2:用动态导入适配CommonJS环境(临时兼容)

如果暂时无法调整加载器配置,可以在jest.config.ts中改用动态导入strip-json-comments——CommonJS模块支持这种写法:

export default async function config() {
  const { default: strip } = await import('strip-json-comments');
  // 调用strip函数处理逻辑
  strip(...);
  // 返回配置对象
  return {
    // 你的Jest配置项
  };
}

注意:这个方案要求Jest版本在28及以上,因为Jest 28才开始支持异步配置函数。

方案3:升级依赖并优化TypeScript配置

确保使用Jest 29+、ts-node最新版和适配的TypeScript版本,同时调整tsconfig.json的ESM相关配置:

{
  "compilerOptions": {
    "module": "ESNext",
    "moduleResolution": "NodeNext",
    "target": "ESNext",
    "esModuleInterop": true,
    "skipLibCheck": true
  },
  "include": ["jest.config.ts", "**/*.spec.ts"]
}

保持package.json中的"type": "module"配置,Jest会结合ts-node/esm加载器正确解析ESM模块。

核心要点

  • Jest加载配置文件的逻辑和测试文件是分开的,即使测试文件能正常跑ESM,配置文件仍需单独指定加载方式。
  • strip-json-comments 4.0+仅支持ESM,所以要么让配置文件以ESM模式加载,要么用动态导入的方式适配CommonJS环境。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 00:04:58