错误&quot“ syntaxerror:无法在模块之外使用导入语句”。在与Typescript开玩笑中使用node-fetch时
我正在尝试使用Jest在打字稿中编写一个集成测试,该测试使用node-fetch
,诸如此类:
import fetch from 'node-fetch';
test('Hello', async () => {
await fetch("http://www.google.com");
});
但是我遇到了以下错误:
Jest encountered an unexpected token
[...]
Details:
/home/xxx/node_modules/node-fetch/src/index.js:9
import http from 'node:http';
^^^^^^
SyntaxError: Cannot use import statement outside a module
> 1 | import fetch from 'node-fetch';
| ^
2 |
3 | test('Hello', async () => {
4 | await fetch("http://www.google.com");
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1796:14)
at Object.<anonymous> (temp.test.ts:1:1)
我尝试了其他问题中给出的一些解决方案工作;我认为我的问题略有不同,因为不是阻止我使用ES6式通常很重要,但是 em 不适合node> node-fetch < /代码>。例如,我可以从“ Express”
中进行导入express
而无需任何困难。
为了重现此错误,我运行:
npm init
npm install --save-dev jest typescript ts-jest @types/jest node-fetch @types/node-fetch
npx ts-jest config:init
npx jest
它产生以下嘲笑配置:
/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
};
I am trying to write an integration test in Typescript with Jest which uses node-fetch
, like this:
import fetch from 'node-fetch';
test('Hello', async () => {
await fetch("http://www.google.com");
});
But I am getting the following error:
Jest encountered an unexpected token
[...]
Details:
/home/xxx/node_modules/node-fetch/src/index.js:9
import http from 'node:http';
^^^^^^
SyntaxError: Cannot use import statement outside a module
> 1 | import fetch from 'node-fetch';
| ^
2 |
3 | test('Hello', async () => {
4 | await fetch("http://www.google.com");
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1796:14)
at Object.<anonymous> (temp.test.ts:1:1)
I have tried some of the solutions given in other questions but they don't work; I think that my problem is slightly different because does not prevent me from using ES6-style important in general, but it specifically does not work for node-fetch
. For example, I can do import express from 'express'
without any difficuly.
To reproduce this error, I ran:
npm init
npm install --save-dev jest typescript ts-jest @types/jest node-fetch @types/node-fetch
npx ts-jest config:init
npx jest
which yields the following Jest config:
/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请使用与CommonJ兼容的V2:
Please use v2 which remains compatible with CommonJS: