Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

require('node-fetch') gives ERR_REQUIRE_ESM

I just use

const fetch = require('node-fetch')

And I get

Error [ERR_REQUIRE_ESM]: require() of ES Module C:\Users\Alex\Desktop\rollbot\node_modules\node-fetch\src\index.js from C:\Users\Alex\Desktop\rollbot\index.js not supported.
Instead change the require of C:\Users\Alex\Desktop\rollbot\node_modules\node-fetch\src\index.js in C:\Users\Alex\Desktop\rollbot\index.js to a 
dynamic import() which is available in all CommonJS modules.
{
  code: 'ERR_REQUIRE_ESM'
}

All my other packages work, just node-fetch does this. What should I do in order to use node-fetch?

like image 649
AlexStr Avatar asked Sep 07 '21 11:09

AlexStr


People also ask

Can I require node-fetch?

As of version 3.0, node-fetch is an ESM-only module - you are not able to import it with require() .

How do I import node-fetch with require?

Use import fetch from 'node-fetch' instead of const fetch = require('node-fetch') to import the package. You also need to put "type": "module" in your package. json and more. Follow the below guide.

How do you solve require () of ES modules is not supported?

You can solve the "[ERR_REQUIRE_ESM]: require() not supported" by doing one of two things: Use ESM - use import foo from 'foo' , instead of const foo = require('foo') and add the following line to your package. json file: "type": "module" . Downgrade to the last version of the package that is built with CommonJS .

How do you fix require is not defined?

To solve the "ReferenceError require is not defined" error, remove the type property if it's set to module in your package. json file and rename any files that have a . mjs extension to have a . js extension.


1 Answers

From the node-fetch package readme:

node-fetch is an ESM-only module - you are not able to import it with require. We recommend you stay on v2 which is built with CommonJS unless you use ESM yourself. We will continue to publish critical bug fixes for it.

If you want to require it, then downgrade to v2.

The other option you have is to use async import('node-fetch').then(...)

like image 68
Konstantin Dinev Avatar answered Sep 23 '22 17:09

Konstantin Dinev