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

如何在TypeScript+Node.js环境下为Jest测试导入ES2020函数

Jest + TypeScript 测试报错修复方案

问题1:dist目录测试文件出现SyntaxError: Cannot use import statement outside a module

原因

Jest默认优先处理CommonJS模块,但项目通过package.json的"type": "module"启用了ES模块,同时Jest扫描到了dist目录下编译后的ES模块格式测试文件,导致解析冲突。

修复步骤

  1. 修改jest.config.js,限定测试文件范围并启用ESM兼容
    配置Jest只处理原TS测试文件,忽略编译后的dist目录,同时让ts-jest适配ES模块:

    /** @type {import('ts-jest').JestConfigWithTsJest} */
    export default {
      preset: 'ts-jest',
      testEnvironment: 'node',
      testMatch: ['<rootDir>/tests/**/*.test.ts'],
      modulePathIgnorePatterns: ['<rootDir>/dist/'],
      transform: {
        '^.+\\.tsx?$': ['ts-jest', { useESM: true }]
      }
    };
    
  2. 保持package.json的ES模块配置
    无需修改"type": "module",该配置是项目ES模块模式的基础,需与Jest配置匹配。


问题2:TS1343 import.meta.url 语法错误

原因

当前tsconfig.json的模块解析模式与import.meta.url的语法要求不匹配,moduleResolution设置为node无法正确识别Node.js ES模块特有的元属性。

修复步骤

更新tsconfig.json的模块相关配置,适配Node.js ES模块规范:

{
  "compilerOptions": {
    "target": "es2022",
    "module": "nodenext",
    "moduleResolution": "nodenext",
    "outDir": "dist",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true,
    "sourceMap": true
  }
}

如果misc.ts中import.meta.url是误添加的代码,直接删除相关行也可解决该报错。


验证修复

执行npm run test,此时Jest会仅处理tests目录下的TS文件,通过ts-jest完成ES模块兼容转译,同时TypeScript语法检查可正常识别import.meta.url。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 00:10:29