Yusinto Ngadiman
May 02, 2019·1 min read

Using es modules in node

hero

Node 12 finally supports native es6 modules without having to name files with the .mjs extension. To start using es6 modules in node, you'll need to be using node 12 and greater and add three things to your package.json file:

  • a "type": "module" property

Use these two flags when executing node to run your app:

  • "--experimental-modules"

    This enables es modules in node.

  • "--es-module-specifier-resolution=node"

    By default extension resolution is disabled. This means you have to specify file extensions in import statements. This flag enables extension resolution so you can import files without specifying their extensions.

So your package.json file should look like this:

package.json

{
  "type": "module",
  "scripts": {
    "start": "node --experimental-modules --es-module-specifier-resolution=node index.js"
  }
}

Then in your app, you can directly import npm packages like so:

import random from 'random-words';
import someModule from './someModule';

console.log(random({exactly:5, wordsPerString: 3}));

where someModule.js is your own module without having to be an .mjs file!

Yay!