引入lodash-es后TypeScript项目Jest测试失败求助
解决Jest测试lodash-es时出现Unexpected token 'export'的问题
方案1:让Jest转译lodash-es
Jest默认不会转译node_modules内的包,但lodash-es是纯ES模块,Jest默认用CommonJS解析会报错。修改jest.config.js,让Jest对lodash-es进行转译:
export default { transform: { '^.+\\.tsx?$': 'ts-jest', }, // 排除node_modules中除lodash-es外的所有包,只转译lodash-es transformIgnorePatterns: [ 'node_modules/(?!lodash-es/)' ], moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'], };
方案2:映射lodash-es到CommonJS版本的lodash
如果不想转译lodash-es,可以直接将其映射为CommonJS格式的lodash包。先安装lodash:
pnpm add lodash -D
再修改jest.config.js:
export default { moduleNameMapper: { '^lodash-es/(.*)$': 'lodash/$1' }, };
方案3:用Babel辅助转译
若前两种方法无效,可配置Babel处理ES模块:
- 安装Babel相关依赖:
pnpm add @babel/core @babel/preset-env @babel/preset-typescript babel-jest -D
- 创建
babel.config.json:
{ "presets": [ ["@babel/preset-env", { "targets": { "node": "current" } }], "@babel/preset-typescript" ] }
- 修改
jest.config.js改用babel-jest转译:
export default { transform: { '^.+\\.(ts|tsx)$': 'babel-jest', }, transformIgnorePatterns: [ 'node_modules/(?!lodash-es/)' ], };
pnpm monorepo额外注意事项
- 确保lodash-es安装在当前子包的
node_modules中,而非根目录,避免Jest路径解析错误。 - 若子包
package.json的type为module,需在jest.config.js中添加ES模块处理配置:
export default { extensionsToTreatAsEsm: ['.ts'], moduleNameMapper: { '^(\\.{1,2}/.*)\\.js$': '$1' }, };
内容的提问来源于stack exchange,提问作者svenema
相关产品推荐
相关产品推荐

