[英]Can't import node-fetch into Typescript
我正在尝试将node-fetch
导入到我的Typescript
项目中,但我遇到了这个错误:
[ERR_REQUIRE_ESM]:必须使用 import 加载 ES 模块:/Users/xxx/xxx/xxx/xxx/xxx/xxx/xxx/node_modules/node-fetch/src/index.js 不支持 ES 模块的 require()。
这是我的设置:
node-fetch
package 在我的项目中导入如下: import fetch from 'node-fetch';'
这是我的tscongif.json
:
{
"compilerOptions": {
"module": "CommonJS",
"sModuleInterop": true,
"target": "ES2020",
"allowJs": true,
"noImplicitAny": true,
"moduleResolution": "node",
"outDir": "dist",
"baseUrl": ".",
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"resolveJsonModule": true,
"typeRoots": [
"src/@types/",
"node_modules/@types",
],
"strict": true,
"strictNullChecks": true,
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"noEmit": true,
"skipLibCheck": true,
},
"include": [
"src/**/*",
"config/**/*"
]
}
我还尝试将"type": "module"
添加到package.json
,并将"module": "ES2020"
设置为tsconfig.json
,但出现新错误:
TypeError [ERR_UNKNOWN_FILE_EXTENSION]:未知文件扩展名“.ts”
要运行我的代码,我使用配置如下的nodemon
:
{
"watch": ["src"],
"ext": "ts, js, json",
"execMap": {
"ts": "NODE_ENV=development ts-node -T"
}
}
v3 的 node-fetch 是一个仅 ESM 的模块 - 根据文档,您无法使用 require() 导入它。
你试过用这个吗:
import * as fetch from 'node-fetch';
您遇到的问题不是您的应用程序代码中的问题,而是由项目配置错误引起的。 ts-node
中的 ESM 支持目前是实验性的。 请参阅此 GitHub 问题以了解当前情况:
https://github.com/TypeStrong/ts-node/issues/1007
根据您在评论中共享的存储库链接中的数据,以及上述问题中的信息和此处的文档说明,以下更改将允许您使用复制存储库中的 npm start:dev
脚本运行您的应用程序。
./package.json
:
将以下条目添加到 object 的顶层(这将告诉 Node 您已转译的*.js
文件是 ES 模块并在该模式下运行它们):
{
"type": "module"
}
./tsconfig.json
:
将compilerOptions.module
的值修改为"esnext"
(这将告诉 TypeScript 以 ESM 格式而不是 CJS 发出模块):
{
"compilerOptions": {
"module": "esnext"
}
}
./nodemon.json
:
将execMap.ts
的值修改为以下内容(以这种方式配置NODE_OPTIONS
环境变量可在ts-node
中启用本机 ESM 支持):
{
"execMap": {
"ts": "NODE_ENV=development NODE_OPTIONS='--loader ts-node/esm' ts-node -T"
}
}
控制台 output:
$ npm run start:dev
> fetch-problem@1.0.0 start:dev
> NODE_ENV=development nodemon ./src/index.ts
[nodemon] 2.0.15
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): src/**/*
[nodemon] watching extensions: ts,js,json
[nodemon] starting `NODE_ENV=development NODE_OPTIONS='--loader ts-node/esm' ts-node -T ./src/index.ts`
(node:3273) ExperimentalWarning: --experimental-loader is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
START
[nodemon] clean exit - waiting for changes before restart
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.