ts-jest无法编译执行ESM【解决步骤】
很常见的错误就是 SyntaxError: Unexpected token 'export',需要确保以下操作,才能解决问题
- tsconfig.json 中 compilerOptions.module 与 target 要设置为 ESNext,compilerOptions.target 也要设置为 ESNext, esModuleInterop 设置为 true, 确定tsc将目标代码编译为 ESM版本。其次 moduleResolution 设置为 'node' 以便能够正确解析路径。
- 如果你的源代码中存在自定义的包,例如使用 rollup 构建,则 rollup.config.js 中要设置指定的模块化规范
import typescript from '@rollup/plugin-typescript';
export default {
input: 'src/index.ts',
output: {
dir: 'dist',
format: 'es'
},
plugins: [typescript()]
};
- jest.config.js 中配置 babel-jest
// jest.config.js 或 package.json 中的 Jest 配置
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
transform: {
'^.+\\.tsx?$': 'ts-jest',
'^.+\\.jsx?$': 'babel-jest', // 使用 babel-jest 进行转换
},
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
// 添加其他 Jest 配置
};
- 在 babel.config.json 中配置预设
{
"presets": ["@babel/preset-env"]
}
- 或者使用 babel.config.js 文件
// babel.config.js
module.exports = {
presets: [
['@babel/preset-env', { targets: { node: 'current' } }]
]
};
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!