简体   繁体   English

Jest Typescript 带有 ES 模块 in node_modules 错误 - 必须使用导入来加载 ES 模块:

[英]Jest Typescript with ES Module in node_modules error - Must use import to load ES Module:

I'm trying to write a simple jest test for a 3rd party package were using that only exports an ES module.我正在尝试为 package 使用的第 3 方编写一个简单的玩笑测试,它只导出一个 ES 模块。 It's a wrapper around an http server.它是http服务器的包装器。

Here is a test repo I setup (just run yarn && yarn jest to reproduce): https://github.com/jamesopti/hocuspocus-testing这是我设置的测试回购协议(只需运行yarn && yarn jest即可重现): https://github.com/jamesopti/hocuspocus-testing

No matter what config I experiment with, I still get this error when trying to run it:无论我试验什么配置,在尝试运行它时我仍然会收到此错误:

 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)', () => {

Things I've tried already:我已经尝试过的事情:

  • The Jest instructions on ES modules: https://jestjs.io/docs/ecmascript-modules Jest 关于 ES 模块的说明: https://jestjs.io/docs/ecmascript-modules

  • In Jest configuration using transformIgnorePatterns在 Jest 配置中使用transformIgnorePatterns

    • transformIgnorePatterns: ['node_modules/(?!@hocuspocus/)']
  • Using Babel via babel-jest通过babel-jest使用 Babel

    • modifying transform setup in Jest configuration as '^.+\.jsx?$': 'babel-jest', '^.+\.tsx?$': 'ts-jest'将 Jest 配置中的转换设置修改为 '^.+\.jsx?$': 'babel-jest', '^.+\.tsx?$': 'ts-jest'

    • Ran into the error You appear to be using a native ECMAScript module configuration file, which is only supported when running Babel asynchronously.遇到错误You appear to be using a native ECMAScript module configuration file, which is only supported when running Babel asynchronously.

    • Using.babel.config.js instead of.babelrc.js使用 .babel.config.js 而不是 .babelrc.js

Any ideas what I'm missing here?任何想法我在这里缺少什么? I thought this would be straightforward我以为这很简单

[EDIT 1] - Added tsconfig.json and a working src/index.ts file to the example repo . [编辑 1] - 添加tsconfig.json和工作src/index.ts文件到示例 repo

So for anyone still hitting this, ESM configuration explained in this section of documentation :因此,对于仍然遇到此问题的任何人,文档的这一部分中解释了 ESM 配置:

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

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

JAN 2023: ES2022, TypeScript 4.9.4, jest 29.3.1, ts-jest 29.0.3 2023 年 1 月:ES2022、TypeScript 4.9.4、玩笑 29.3.1、ts-玩笑 29.0.3

This is what worked for me, after 2 hours of frustration.经过 2 小时的挫折,这对我有用。 I used this configuration in jest.config.ts :我在jest.config.ts中使用了这个配置:

import type { JestConfigWithTsJest } from 'ts-jest'

const config: JestConfigWithTsJest = {
  extensionsToTreatAsEsm: ['.ts'],
  verbose: true,
  preset: 'ts-jest/presets/default-esm',
  testEnvironment: 'node',
  transform: {
    '^.+\\.(ts|tsx)?$': ['ts-jest', { useESM: true }]
  },
  testPathIgnorePatterns: ['./dist']
}

export default config

Change the test script in package.json to:package.json中的test脚本改为:

I use pnpm .我使用pnpm Change to npx jest with npm, or yarn exec with yarn使用 npm 更改为 npx npx jest ,或使用yarn exec yarn

...
"scripts": {
  ...
  "test": "NODE_OPTIONS=--experimental-vm-modules pnpm exec jest",
  ...
}
...

tsconfig.json : tsconfig.json

{
  "compilerOptions": {
    "rootDirs": ["src"],
    "outDir": "dist",
    "lib": ["ES2022"],
    "target": "ES2022",
    "module": "ES2022",
    "composite": true,
    "moduleResolution": "node",
    "declaration": true,
    "declarationMap": true,
    "incremental": true,
    "esModuleInterop": true,
    "types": ["jest", "node", "@types/jest"],
    "sourceMap": true
  },
  "ts-node": {
    "esm": true,
    "experimentalSpecifierResolution": "node"
  },
  "include": ["./src/**/*", "./tests/**/*"]
}

See this (rather confusing) documentation for reference: https://kulshekhar.github.io/ts-jest/docs/guides/esm-support/请参阅此(相当混乱)文档以供参考: https://kulshekhar.github.io/ts-jest/docs/guides/esm-support/

You don't have a tsconfig.json file that specifies module .您没有指定moduletsconfig.json文件。 Therefore it uses the default, where it transpiles all your modules to CommonJS syntax, which uses require .因此,它使用默认值,将所有模块转换为使用require CommonJS语法。

If you actually look at your dist/hocuspocus-server.esm.js , you should see it using require over the ESM import syntax.如果你真的查看你的dist/hocuspocus-server.esm.js ,你应该看到它使用require而不是 ESM 导入语法。

I was having the same problem with my svelte app and testing.我的 svelte 应用程序和测试遇到了同样的问题。 I ultimately traced it to having a jest.config.js and a jest.config.json in my root folder.我最终追踪到在我的根文件夹中有一个jest.config.js和一个jest.config.json It seems that jest does not have automatic config file resolution and was using a default configuration instead of either of my specified configurations.似乎 jest 没有自动配置文件解析,而是使用默认配置而不是我指定的配置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM