Reputation: 15837
I'm trying to use node-fetch
v3 with nodemon
+ ts-node
, but I got all possible errors about ESM. I've tried many combination of type
in the package.json
file and compilerOptions.target
in the tsconfig.json
file, but I'm not able to simultaneously compile my script and run it in development mode.
This is my simple script:
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);
I need to be able to make it work with following two commands:
tsc && node index.js
nodemon -r ts-node index.ts
How should be package.json
and tsconfig.json
configured to make both the commands to work?
Please note that the problems start as soon as I add node-fetch
to the project.
Upvotes: 6
Views: 4952
Reputation: 927
It is currently very hard to compile typescript to native ESM I recommend downgrading node-fetch to 2.6.5
.
Node Fetch started shipping ES Modules since 3.0.0
see here:
https://github.com/node-fetch/node-fetch/blob/main/docs/v3-UPGRADE-GUIDE.md#breaking
If you want to go the hard route you can follow this blog: https://2ality.com/2021/06/typescript-esm-nodejs.html
The problem is that you cannot use require('some-module')
which is built to be an ESM.
Since you're compiling to commonjs modules it will require some transpiling to make them work with ESM.
Typescript is adding nodenext
as a module option on typescript 4.5
Upvotes: 11