node.js - 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)', () => {
我已经尝试过的事情:
ES 模块的 Jest 说明:https ://jestjs.io/docs/ecmascript-modules
在 Jest 配置中使用
transformIgnorePatterns
transformIgnorePatterns: ['node_modules/(?!@hocuspocus/)']
通过使用 Babel
babel-jest
将 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] -在示例 repotsconfig.json
中添加了一个工作src/index.ts
文件。
解决方案
因此,对于仍然遇到此问题的任何人,本部分文档中解释了 ESM 配置:
https://kulshekhar.github.io/ts-jest/docs/guides/esm-support
{
// [...]
"jest": {
"extensionsToTreatAsEsm": [".ts"],
"globals": {
"ts-jest": {
"useESM": true
}
}
}
}
推荐阅读
- ios - 冷启动和热启动有什么区别?
- awk - awk 脚本额外输出:打印原始行(已读取)以及已处理的行
- spring-boot - SecurityContextHolder.getContext().getAuthentication() 返回 null
- passport.js - hasura auth hook 不转发客户端 cookie
- sql - 如何将逗号分隔的数据从一列拆分为多行
- c# - 将数据插入嵌套列表 C#
- mongoose - 如何使用 jest 检查调用次数的猫鼬模拟函数?
- python - Python 在不停止执行代码的情况下捕获自定义警告类
- javascript - 如何使用 Javascript 将特定文件附加到 FormData?
- algorithm - 随机选择顶点作为信标