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

TypeScript+ESM环境下Jest路径别名失效问题求助

Fixing ESM + TypeScript Path Alias Issues in Jest

It looks like the core issue here is that ESM requires .js suffixes in imports, but the default path alias mappings generated by pathsToModuleNameMapper don't account for these suffixes. When Jest tries to resolve @src/modules/mangleTypes.js, it maps it to source/modules/mangleTypes.js—which doesn't exist (your actual source file is .ts). Here's how to fix this:

Step-by-Step Solution

1. Extend Module Name Mapper to Handle .js Suffixes

Update your jest.config.ts to add custom mappings that capture and strip the .js suffix from imports, pointing them to your actual .ts source files:

import type { Config } from '@jest/types';
import { pathsToModuleNameMapper } from 'ts-jest';
import tsconfigJson from './tsconfig.json';

// Generate base mappings from tsconfig
const baseMappers = pathsToModuleNameMapper(tsconfigJson.compilerOptions.paths, { prefix: '<rootDir>/' });

// Add rules to handle .js suffixes in ESM imports
const extendedMappers = {
  ...baseMappers,
  '^@src/(.*)\\.js$': '<rootDir>/source/$1.ts',
  '^@/(.*)\\.js$': '<rootDir>/source/$1.ts',
  '^@test/(.*)\\.js$': '<rootDir>/test/$1.ts',
  '^@test\\.js$': '<rootDir>/test.ts', // Handle direct @test.js imports if needed
};

const config: Config.InitialOptions = {
  preset: 'ts-jest/presets/default-esm',
  testEnvironment: 'node',
  verbose: true,
  globals: {
    'ts-jest': {
      tsconfig: './tsconfig.json',
      useESM: true
    }
  },
  moduleNameMapper: extendedMappers,
  transformIgnorePatterns: ['<rootDir>/node_modules/'],
  // Tell Jest to treat .ts files as ESM modules
  extensionsToTreatAsEsm: ['.ts']
};

export default config;

2. Verify TS Config Compatibility

Your existing tsconfig.json is already correctly set up for ESM (with module: Node16 and moduleResolution: Node16), but double-check that:

  • allowImportingTsExtensions is disabled (default behavior, since ESM requires .js suffixes)
  • include covers your source and test directories (which you've done)

3. Clear Jest Cache (If Needed)

Sometimes cached resolution rules can cause issues. Run this command to reset the cache before re-running tests:

npx jest --clearCache

Why This Works

The default mappings from pathsToModuleNameMapper only match paths without .js suffixes. By adding the new regex rules, we:

  1. Capture imports like @src/modules/mangleTypes.js
  2. Map them to the actual .ts file at source/modules/mangleTypes.ts
  3. Ensure Jest treats your TypeScript files as ESM modules with extensionsToTreatAsEsm

This aligns ESM's strict import requirements with Jest's path alias resolution.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 21:38:10