首页 > 解决方案 > Jest Typescript with ES Module in node_modules 错误 - 必须使用导入来加载 ES 模块:

问题描述

我正在尝试为使用仅导出 ES 模块的 3rd 方包编写一个简单的笑话测试。它是围绕服务器的包装器http

这是我设置的一个测试仓库(只是运行yarn && yarn jest来重现):https ://github.com/jamesopti/hocuspocus-testing

无论我尝试什么配置,尝试运行它时仍然会出现此错误:

 Must use import to load ES Module: /Users/j/hocuspocus-testing/node_modules/@hocuspocus/server/dist/hocuspocus-server.esm.js

    > 1 | import { Server, Hocuspocus } from '@hocuspocus/server'
        | ^
      2 | import * as request from 'supertest'
      3 |
      4 | describe('Server (e2e)', () => {

我已经尝试过的事情:

有什么想法我在这里想念的吗?我认为这很简单

[编辑 1] -在示例 repotsconfig.json中添加了一个工作src/index.ts文件。

标签: node.jstypescriptjestjses6-modules

解决方案


因此,对于仍然遇到此问题的任何人,本部分文档中解释了 ESM 配置:

https://kulshekhar.github.io/ts-jest/docs/guides/esm-support

{
  // [...]
  "jest": {
    "extensionsToTreatAsEsm": [".ts"],
    "globals": {
      "ts-jest": {
        "useESM": true
      }
    }
  }
}

推荐阅读