Use ES6 modules in Node.js?

Before Node version 13, we were using the esm npm package and run our app.js using the commandnode -r esm app.js

With recent updates of Node, this is natively supported now. There are two ways we can achieve it

  • Save the file with .mjs extension.
  • Add { "type": "module" } in the nearest package.json.

Note that we only have to do one thing from the above mentioned.

If we are using Node.js version 8–12, save the file with ES6 modules with .mjs extension and run it like:

node --experimental-modules app.mjs

Leaving a clap will motivate me to write more useful tips related to JS.

--

--