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

Jest测试node_modules文件解析失败,配置调整无效求助

解决Jest测试中@ms/centr-loader的SyntaxError: Unexpected token 'export'问题

这个错误的核心原因是:Jest默认不会转译node_modules目录下的文件,但@ms/centr-loader使用了未转译的ES模块语法(export),而Node.js/Jest的默认运行环境只支持CommonJS模块。以下是针对性的排查和修复步骤:

1. 调整Jest的转译忽略规则

修改jest.config.ts,将@ms/centr-loader从transformIgnorePatterns的忽略列表中排除,让Jest对其进行转译:

export default {
  // 保留原有其他配置
  transform: {
    '^.+\\.(ts|tsx)$': 'ts-jest',
    '^.+\\.(js|jsx)$': 'babel-jest',
  },
  transformIgnorePatterns: [
    // 排除@ms/centr-loader,允许Jest转译它
    '/node_modules/(?!@ms/centr-loader)',
  ],
};

注意:如果你的Jest配置是JS格式(jest.config.js),只需将导出语法改为CommonJS格式即可。

2. 确保Babel配置正确处理ES模块

检查.babelrc(或babel.config.js),确认已配置@babel/preset-env并针对当前Node环境转译:

{
  "presets": [
    ["@babel/preset-env", { "targets": { "node": "current" } }],
    "@babel/preset-typescript" // 若项目使用TypeScript则添加
  ]
}

targets.node: "current"会让Babel根据你运行Jest的Node版本,将ES模块语法转译为兼容的CommonJS代码。

3. 验证TypeScript配置(TypeScript项目)

如果你的项目基于TypeScript,检查tsconfig.json的compilerOptions,确保模块系统设置为CommonJS:

{
  "compilerOptions": {
    "module": "CommonJS",
    "target": "ES6",
    // 保留其他原有配置
  }
}

Jest在Node环境下默认使用CommonJS模块解析,module: "CommonJS"能确保TypeScript编译后的代码和Jest的运行环境兼容。

4. 额外排查步骤

  • 清理Jest缓存:运行jest --clearCache,缓存可能导致新配置无法生效。
  • 检查moduleNameMapper:确保没有错误映射@ms/centr-loader,导致Jest加载了未转译的文件。
  • 核对模块版本:确认@ms/centr-loader的版本是否存在ES模块未转译的已知问题,必要时尝试升级或降级版本。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 23:26:08