Error: require() of ES modules is not supported when importing node-fetch

From the Upgrade Guide

node-fetch was converted to be a ESM only package in version 3.0.0-beta.10. node-fetch is an ESM-only module – you are not able to import it with require.

Alternatively, you can use the async import() function from CommonJS to load node-fetch asynchronously:

// mod.cjs
const fetch = (...args) => import('node-fetch').then(({default: fetch}) => fetch(...args));

or you stay on v2 as they say in the README

node-fetch is an ESM-only module – you are not able to import it with require. We recommend you stay on v2 which is built with CommonJS unless you use ESM yourself. We will continue to publish critical bug fixes for it.

EDIT

I saw that in the doc, used it, and the script crashes with :

error TS2556: A spread argument must either have a tuple type or be passed to a rest parameter.

Since you are using typescript you should do something like this

import { RequestInfo, RequestInit } from "node-fetch";

const fetch = (url: RequestInfo, init?: RequestInit) =>  import("node-fetch").then(({ default: fetch }) => fetch(url, init));

Leave a Comment