6

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.

1 Answer 1

11

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, interesting reading. I'll not follow your suggestion, I prefer the hard route: one of the purposes of my question is to understand how to work with ESM modules.
I don't really understand the issue. I also don't want to spend time researching. I just want to be able to npm i node-fetch and be able to import fetch from 'node-fetch' in my typescript projects. Shouldn't be an issue today! Back to node-fetch@2 for me
the absolute state of js, expect this issue to occur for more packages soon.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.