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

使用Jest测试TypeScript代码时无法识别lodash-es依赖的问题

解决Jest无法识别lodash-es依赖的问题

问题根源

lodash-es采用ES模块语法(export/import),而Jest默认不会转译node_modules目录下的文件,导致无法解析ES模块语法,抛出SyntaxError: Unexpected token 'export'。

解决方案

方案一:让Jest转译lodash-es

修改Jest配置,调整transformIgnorePatterns明确告知Jest不要忽略lodash-es,同时完善转译规则覆盖对应文件:

module.exports = {
  preset: "ts-jest",
  transform: {
    "^.+\\.tsx?$": "ts-jest", // 确保TS文件由ts-jest处理
    "^.+\\.js$": "babel-jest", // 包含lodash-es在内的JS文件由babel-jest处理
  },
  // 仅忽略node_modules中除lodash-es外的其他包
  transformIgnorePatterns: ["/node_modules/(?!lodash-es)/"],
};

同时确保你的Babel配置(babel.config.js或.babelrc)包含@babel/preset-env,以支持ES模块转译:

module.exports = {
  presets: [
    ["@babel/preset-env", { targets: { node: "current" } }],
  ],
};

方案二:映射到CommonJS版本的lodash

如果测试环境不需要tree-shaking特性,可以直接把lodash-es映射为CommonJS版本的lodash,Jest能直接解析该版本:

module.exports = {
  preset: "ts-jest",
  transform: {
    "^.+\\.tsx?$": "ts-jest",
  },
  moduleNameMapper: {
    "^lodash-es$": "lodash",
  },
};

这种方式无需额外配置Babel,实现更简洁。

验证

修改配置后重新运行Jest测试,即可正常解析lodash-es的导入语句。

内容的提问来源于stack exchange,提问作者許勝翔

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 16:57:41