ts-jest无法编译执行ESM【解决步骤】

很常见的错误就是 SyntaxError: Unexpected token 'export',需要确保以下操作,才能解决问题

  1. tsconfig.json 中 compilerOptions.module 与 target 要设置为 ESNext,compilerOptions.target 也要设置为 ESNext, esModuleInterop 设置为 true, 确定tsc将目标代码编译为 ESM版本。其次 moduleResolution 设置为 'node' 以便能够正确解析路径。
  2. 如果你的源代码中存在自定义的包,例如使用 rollup 构建,则 rollup.config.js 中要设置指定的模块化规范
import typescript from '@rollup/plugin-typescript';

export default {
  input: 'src/index.ts',
  output: {
    dir: 'dist',
    format: 'es'
  },
  plugins: [typescript()]
};
  1. 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 配置
};
  1. 在 babel.config.json 中配置预设
{
  "presets": ["@babel/preset-env"]
}
  1. 或者使用 babel.config.js 文件
// babel.config.js
module.exports = {
  presets: [
    ['@babel/preset-env', { targets: { node: 'current' } }]
  ]
};
posted @ 2024-03-30 14:54  TateWang  阅读(51)  评论(0编辑  收藏  举报
Top