gpt4 book ai didi

node.js - 在 node_modules 错误中带有 ES 模块的 Jest Typescript - 必须使用导入来加载 ES 模块 :

转载 作者:行者123 更新时间:2023-12-04 14:53:53 24 4
gpt4 key购买 nike

我正在尝试为仅导出 ES 模块的 3rd 方包编写一个简单的 Jest 测试。它是 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)', () => {
我已经尝试过的东西:
  • ES 模块的 Jest 说明:https://jestjs.io/docs/ecmascript-modules
  • 在 Jest 配置中使用 transformIgnorePatterns
  • transformIgnorePatterns: ['node_modules/(?!@hocuspocus/)']

  • 通过 babel-jest 使用 Babel
  • 将 Jest 配置中的转换设置修改为 '^.+\.jsx?$': 'babel-jest', '^.+\.tsx?$': 'ts-jest'
  • 遇到错误 You appear to be using a native ECMAScript module configuration file, which is only supported when running Babel asynchronously.
  • 使用 .babel.config.js 而不是 .babelrc.js


  • 有什么想法我在这里想念的吗?我认为这很简单
    [编辑 1] - 新增 tsconfig.json和一个工作 src/index.ts文件到 the example repo .

    最佳答案

    因此,对于仍然遇到此问题的任何人,文档的这一部分中解释了 ESM 配置:
    https://kulshekhar.github.io/ts-jest/docs/guides/esm-support

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

    关于node.js - 在 node_modules 错误中带有 ES 模块的 Jest Typescript - 必须使用导入来加载 ES 模块 :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68520619/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com