NodeJS "Must use import to load ES Module"

I ran your code with no problem. Check for 2 things:

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

Hope this helps:

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 version than the one used to install packages in this project.

I had two options:

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

I chose the first approach and it worked for me.

I didn't want to post another question regarding the same so I posted an answer here.