To fix ‘Error: require() of ES modules is not supported when importing node-fetch’, we call the import function.
For instance, we write
import { RequestInfo, RequestInit } from "node-fetch";
const fetch = async (url: RequestInfo, init?: RequestInit) => {
const { default: fetch } = await import("node-fetch");
return fetch(url, init);
};
to define the fetch function that calls import to import node-fetch.
And then we get the fetch function from the returned promise with await and destructuring.
Finally, we return the promise returned by calling fetch with the url and init object.