How do I use ES6 modules in Node 12 without getting `ERR_REQUIRE_ESM`?

I’m trying to experiment with ES6 modules in Node.js 12, but I keep running into the following error:

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /path/to/src/index.mjs

I’ve read that Node 12 supports ES6 modules, but I’m not sure how to set up a minimal project correctly to avoid this. Here’s what my package.json looks like (simplified):

{
  "name": "dynamic-es6-mod",
  "version": "1.0.0",
  "main": "src/index.mjs",
  "scripts": {
    "start": "node src/index.mjs"
  },
  "dependencies": {
    "globby": "^10.0.1"
  }
}

When I run:

$ node -v
12.6.0
$ npm run start

I get the ERR_REQUIRE_ESM error.

How can I set up a minimal ES6 module project in Node 12 that avoids this error? What configuration or file changes are required to correctly use import/export syntax in Node 12?

Any examples or guidance on fixing err_require_esm would be really helpful.

I hit this error too. Node 12 needs a hint in your package.json to treat .js files as ES modules:

{
  "type": "module"
}

Alternatively, rename your files to .mjs and run them with node filename.mjs.

In my projects, I also needed to make sure I wasn’t mixing require with import. Node doesn’t allow require() for ES modules, so everything importing the module needs to use import.

If you need backward compatibility with CommonJS, I created a separate build for Node 12 using Babel. That way, I could use ES6 syntax and transpile for Node 12 without ERR_REQUIRE_ESM.