TypeScript+ESM环境下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:
allowImportingTsExtensionsis disabled (default behavior, since ESM requires.jssuffixes)includecovers yoursourceandtestdirectories (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:
- Capture imports like
@src/modules/mangleTypes.js - Map them to the actual
.tsfile atsource/modules/mangleTypes.ts - 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

