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

Jest无法解析TypeScript ESM路径映射,缺失哪些配置?

解决Jest无法解析路径映射的问题

缺失的配置及修复步骤

  1. 启用项目ESM模式
    在package.json中添加:
"type": "module"

使用NodeNext模块系统时,必须明确声明项目为ESM,否则Jest处理导入会出现兼容性问题。

  1. 让ts-jest读取tsconfig的路径配置
    修改jest.config.ts里的ts-jest配置,添加tsconfig字段指向你的配置文件,这样ts-jest才能识别paths映射规则:
transform: {
  "^.+\\.ts?$": [
    "ts-jest",
    {
      useESM: true,
      tsconfig: "./tsconfig.json" // 新增此行
    },
  ],
},
  1. 修正moduleNameMapper适配ESM扩展名要求
    NodeNext的ESM模式下,导入必须带文件扩展名,所以调整moduleNameMapper,同时处理路径映射和扩展名问题:
moduleNameMapper: {
  "^@App/(.*)$": "<rootDir>/src/$1",
  "^(\\.{1,2}/.*)\\.js$": "$1"
},
  1. 为测试文件单独配置tsconfig(可选但推荐)
    主tsconfig.json排除了__test__目录,编辑器可能无法识别测试文件里的路径映射。可以创建tsconfig.test.json:
{
  "extends": "./tsconfig.json",
  "exclude": ["node_modules", "./*.ts"],
  "include": ["__test__/**/*", "src/**/*"]
}

然后把jest.config.ts里的tsconfig路径改成./tsconfig.test.json。

修复后的完整jest.config.ts

import type { JestConfigWithTsJest } from "ts-jest";

const config: JestConfigWithTsJest = {
  verbose: true,
  transform: {
    "^.+\\.ts?$": [
      "ts-jest",
      {
        useESM: true,
        tsconfig: "./tsconfig.test.json"
      },
    ],
  },
  extensionsToTreatAsEsm: [".ts"],
  moduleNameMapper: {
    "^@App/(.*)$": "<rootDir>/src/$1",
    "^(\\.{1,2}/.*)\\.js$": "$1"
  },
};

export default config;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 02:06:07