Categories
JavaScript Answers

How to fix ‘Error: require() of ES modules is not supported’ when importing node-fetch?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *