Borislav Hadzhiev
Last updated: Jul 25, 2022
Photo from Unsplash
The node-fetch error "[ERR_REQUIRE_ESM]: require() not supported" occurs because
the node-fetch
package has been converted to be an ESM only package in version
3
, which means that the package cannot be imported with require()
anymore.
To solve the node-fetch error "[ERR_REQUIRE_ESM]: require() not supported",
use a dynamic import to import the node-fetch
package or downgrade the version
of the package to 2.6.6
, which is the last version that is built with
CommonJS
.
Here is how to import the node-fetch
package using a dynamic import in
JavaScript and TypeScript.
// ✅ Do this if using JAVASCRIPT const fetch = (...args) => import('node-fetch').then(({ default: fetch }) => fetch(...args)); // ✅ Do this if using TYPESCRIPT import { RequestInfo, RequestInit } from 'node-fetch'; const fetch = (url: RequestInfo, init?: RequestInit) => import('node-fetch').then(({ default: fetch }) => fetch(url, init));
You can read more about the breaking changes in the node-fetch
package in
their
GitHub upgrade guide.
If your environment supports ES Modules, you should try to convert the
require()
import to ESM.
import fetch from 'fetch'; console.log(fetch)
But this might not work depending on your setup.
Alternatively, you can downgrade the node-fetch
package to version 2.6.6
and still use the require
syntax. Version 2
of the node-fetch
package is
built with CommonJS
.
2
.To downgrade to version 2.6.6
, open your terminal in the root directory of
your project and run the following commands.
npm install node-fetch@2.6.6 # 👇️ NOTE: you only need this if using TypeScript npm install --save-dev @types/node-fetch@2.x
Make sure to only install the type definitions if you're using TypeScript.
node-fetch
package starting at version 3.x
, but if you use version 2.x
, you have to install them separately.Now you can use the require()
syntax to import the node-fetch
package.
const fetch = require('node-fetch'); console.log(fetch);