th3*_*man 14 node.js 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包被导入到我的项目中,如下所示: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/**/*"
]
}
Run Code Online (Sandbox Code Playgroud)
我还尝试添加"type": "module"到package.json并设置"module": "ES2020"到 中tsconfig.json,但出现了新错误:
类型错误 [ERR_UNKNOWN_FILE_EXTENSION]:未知的文件扩展名“.ts”
要运行我的代码,我使用nodemon配置如下:
{
"watch": ["src"],
"ext": "ts, js, json",
"execMap": {
"ts": "NODE_ENV=development ts-node -T"
}
}
Run Code Online (Sandbox Code Playgroud)
您遇到的问题不是应用程序代码中的问题,而是由项目配置错误引起的。ESM 支持ts-node目前处于实验阶段。请参阅此 GitHub 问题以了解当前情况:
https://github.com/TypeStrong/ts-node/issues/1007
根据您在评论中共享的存储库链接中的数据,以及上述问题中的信息和此处的文档注释,以下更改将允许您使用复制存储库中的 npm 脚本运行您的应用程序。start:dev
./package.json:
将以下条目添加到对象的顶层(这将告诉 Node 您的转译*.js文件是 ES 模块并在该模式下运行它们):
{
"type": "module"
}
Run Code Online (Sandbox Code Playgroud)
./tsconfig.json:
修改compilerOptions.moduleto的值"esnext"(这将告诉 TypeScript 以 ESM 格式而不是 CJS 发出模块):
{
"compilerOptions": {
"module": "esnext"
}
}
Run Code Online (Sandbox Code Playgroud)
./nodemon.json:
将的值修改execMap.ts为以下内容(NODE_OPTIONS以这种方式配置环境变量可启用 中的本机 ESM 支持ts-node):
{
"execMap": {
"ts": "NODE_ENV=development NODE_OPTIONS='--loader ts-node/esm' ts-node -T"
}
}
Run Code Online (Sandbox Code Playgroud)
控制台输出:
$ 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17343 次 |
| 最近记录: |