gpt4 book ai didi

node.js - ERR_REQUIRE_ESM - TypeScript + nodemon + ts-node + node-fetch

转载 作者:行者123 更新时间:2023-12-05 08:46:24 24 4
gpt4 key购买 nike

我正在尝试将 node-fetch v3 与 nodemon + ts-node 一起使用,但我遇到了有关 ESM 的所有可能错误。我尝试了 package.json 文件中的 typetsconfig.json 中的 compilerOptions.target 的多种组合> 文件,但我无法同时编译我的脚本并在开发模式下运行它。

这是我的简单脚本:

import express from "express";
import fetch from "node-fetch";
import json from "json-server";

const app = express();

app.use("/db", json.router("db.json"));

app.use("/test", (req, res) => {
fetch("http://localhost:3001/db");
res.json({ ok: true });
});

app.listen(3001);

我需要能够使用以下两个命令使其工作:

tsc && node index.js
nodemon -r ts-node index.ts

应该如何配置 package.jsontsconfig.json 才能使这两个命令都起作用?

请注意,一旦我将 node-fetch 添加到项目中,问题就开始了。

最佳答案

目前很难将 typescript 编译为原生 ESM 我建议将 node-fetch 降级到 2.6.5

Node Fetch 从 3.0.0 开始发布 ES 模块,请看这里: https://github.com/node-fetch/node-fetch/blob/main/docs/v3-UPGRADE-GUIDE.md#breaking

如果你想走艰难的路,你可以关注这个博客:https://2ality.com/2021/06/typescript-esm-nodejs.html

问题是您不能使用构建为 ESM 的 require('some-module')。由于您要编译为 commonjs 模块,因此需要进行一些转译才能使它们与 ESM 一起使用。

Typescript 在 typescript 4.5 上添加 nodenext 作为模块选项

关于node.js - ERR_REQUIRE_ESM - TypeScript + nodemon + ts-node + node-fetch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69613588/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com