Borislav Hadzhiev
Fri Feb 18 2022·2 min read
Photo by Lana Campher
The error "[ERR_REQUIRE_ESM]: require() not supported" occurs because a package
you are importing has been converted to be an ESM only package, which means that
the package cannot be imported with require()
anymore.
You can solve the "[ERR_REQUIRE_ESM]: require() not supported" by doing one of two things:
import foo from 'foo'
, instead of
const foo = require('foo')
and add the following line to your
package.json
file: "type": "module"
.CommonJS
.
(Preferred approach if you're using TypeScript).TypeScript
is to downgrade the version of the package to one that is built using CommonJS.You can see which package is causing the error by looking at the error message
in your terminal. The error message in the screenshot above shows that the
node-fetch
package is causing the error.
If any of the following packages are causing the error click on the link to find the fix, otherwise keep reading:
If you go with using ES Modules, you won't be able to use the require()
syntax
to import any other packages and need to update your import statements to ESM.
// 👇️ default import import fetch from 'node-fetch' // 👇️ named import import {myPackage} from 'my-package'
And you have to add the following line to your package.json
file:
{ "type": "module", // 👇️ ...rest }
You can read more about migrating from CommonJS to ESM by visiting this helpful Github Readme.
For example, the node-fetch
package has been converted to be an ESM only
package in version 3
, so we have to downgrade to version 2.6.6
, which is the
last version that is built with CommonJS
and enables us to use the require()
syntax.
To downgrade a package to a specific version, open your terminal in the root directory of your project and run a command that installs the specific version.
npm install node-fetch@2.6.6 # 👇️ NOTE: you only need this if using TypeScript npm install --save-dev @types/node-fetch@2.x
You can use the npm install package@X.X.X
syntax to install a specific version
of a package.
Once you have installed a version of the package that is built using CommonJS,
you will be able to import the package using require()
.
I strongly suggest you read this GitHub Readme if you want to learn more about why this error occurs and possible fixes.