Importing in Node.js: error "Must use import to load ES Module" [duplicate]

Use version 2:

npm install node-fetch@2

node-fetch from v3 is an ESM-only module - you are not able to import it with require().

If you cannot switch to ESM, please use v2 which remains compatible with CommonJS. Critical bug fixes will continue to be published for v2.


I ran your code without any problems. Check for two things:

  1. Node.js version >= 14. It only works with the latest version of Node.js.
  2. Make sure your package.json includes a line for "type": "module". Without this line, Node.js assumes you want to use CommonJS modules rather than ESM.

I ran into a similar issue while building my React project.

Here's the error:

ERROR in ./src/index.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /home/pradeep/Work/my_project/node_modules/@babel/runtime/helpers/interopRequireWildcard/_index.mjs

Then I realized that I am on a different Node.js version than the one used to install packages in this project.

I had two options:

  1. Change Node.js version to the one required by this project and build again.
  2. Stay on the Node.js version you have and remove the node_modules directory and package-lock.json file and do npm install again.

I chose the first approach and it worked for me.


If you have Node.js version lower than 14, e.g., v12 - you must specify this flag:

node --experimental-modules your.mjs

I use nvm to install the latest stable version of Node.js.

To delete the package-lock.json file and the node_modules folder, run npm. I then npm start to solve my problem.