Borislav Hadzhiev
Reading time·2 min
Photo from Unsplash
The node-fetch error "[ERR_REQUIRE_ESM]: require() of ES Module 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() of ES Module not
supported", use a dynamic import to import the node-fetch
package or downgrade
the version of the package to 2.6.7
, 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.7
and use the require
syntax.
Version 2
of the node-fetch
package is built with CommonJS
.
2
.To downgrade to version 2.6.7
, open your terminal in the root directory of
your project and run the following commands.
npm install node-fetch@2.6.7 # 👇️ 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);
If you still get the error, open your package.json
file and make sure you have
version 2.6.7
of node-fetch
installed.
{ "dependencies": { "node-fetch": "^2.6.7" }, "devDependencies": { "@types/node-fetch": "^2.6.2", } }
You can also try to uninstall the package and then install version 2.6.7
.
npm uninstall node-fetch npm install node-fetch@2.6.7
Check out this GitHub Readme if you want to learn more about why this error occurs and possible fixes.
To solve the node-fetch error "[ERR_REQUIRE_ESM]: require() of ES Module not
supported", use a dynamic import to import the node-fetch
package or downgrade
the version of the package to 2.6.7
, which is the last version that is built
with CommonJS
.