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

ts-jest未转译动态导入模块触发SyntaxError如何解决?

问题根因

你遇到的报错本质是两个原因导致:

  1. 你配置的rootDir为./src/test,不在该目录下的TS文件(比如你配置的globalSetup对应的../setup/test_setup.ts)不会被ts-jest转译,直接作为原生JS运行时遇到ESM语法就会抛出错误
  2. 部分node_modules依赖(比如报错的sequelize)已经采用ESM规范导出,jest默认不会转译node_modules内的代码,遇到ESM语法也会报错
解决方案

步骤1:调整jest.config.js配置

修改后的完整配置如下:

/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */
module.exports = {
    preset: 'ts-jest',
    testEnvironment: 'node',
    // 将rootDir调整为项目根目录,保证所有业务TS文件都能被转译
    rootDir: './',
    // 明确匹配测试文件的路径
    testMatch: ['<rootDir>/src/test/**/*.test.ts'],
    // 调整globalSetup的绝对路径
    globalSetup: '<rootDir>/src/setup/test_setup.ts',
    // 配置转译白名单,让jest转译node_modules中的sequelize模块
    transformIgnorePatterns: [
        'node_modules/(?!(sequelize)/)'
    ],
    // 明确TS文件的转译规则
    transform: {
        '^.+\\.tsx?$': ['ts-jest', {
            // 如果你的项目用ESM规范则设为true,用CommonJS规范则设为false
            useESM: false
        }]
    },
    // 配置jest识别的模块后缀
    moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
};

步骤2:校验tsconfig.json配置

确保你的tsconfig.json中包含以下配置,保证模块兼容性:

{
  "compilerOptions": {
    "target": "ES2020",
    // 项目用CommonJS则设为CommonJS,用ESM则设为NodeNext
    "module": "CommonJS",
    "moduleResolution": "Node",
    "esModuleInterop": true,
    "skipLibCheck": true,
    "strict": true
  }
}

可选:特殊场景兼容

如果以上配置修改后仍有报错,可以安装@babel/preset-env和babel-jest,搭配ts-jest做混合转译,覆盖更多ESM语法兼容场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 02:24:02