DEV Community

Cover image for ES6 Modules in Node

Posted on

ES6 Modules in Node

Tale of Two Options

For a long time, JavaScript existed without a clear standard for modules. That wasn’t a problem in the beginning, but as projects grew larger and more complex, there was a growing need for standardization as independent communities sprung up to invent their own ways of organize code. Two popular standards exist today:

  • CommonJS (Node) – the module system created for Node.
  • ES6 Modules (Native) – the specification written by ECMA TC39.

Because ES6 is the official specification, the Node community has made experimental strides to allow ES6 modules when working with Node.


In Node, importing and exporting has traditionally worked like this:

// index.js
var someVar = require("./constant");
console.log(someVar); // 33

// constant.js
const MPG = 33;
module.exports = MPG;
Enter fullscreen mode Exit fullscreen mode

Now if you're running Node 13.x and above, you can use the ES6 modules syntax. Experimental support is enabled by default. You can achieve this by either:

  • Using the .mjs extension
  • Adding {"type": "module"} in the nearest parent package.json file.

Note that Node will treat all other forms as CommonJS, and this is for backwards compatibility.

The Node docs also recommends that it's best to be explicit about whether Node should treat a file as a CommonJS module or an ES6 module. You can achieve this by either:

  • Saving the JS file with .cjs extension.

  • Adding {"type": "commonjs"} in the nearest parent package.json file.


Here, I've opted to change one line in package.json as opposed to renaming all of my JS files with a cjs extension.

// index.js
import fuelEconomy from "./constant.js"
console.log(fuelEconomy); // 33

// constant.js
const MPG = 33;
export default MPG;

// package.json
  "type": "module"
Enter fullscreen mode Exit fullscreen mode

Here's the takeaway from all of this. You have two good options in Node: ES6 and CommonJS. You must choose one. You cannot selectively load some pieces of code as ES6 and other pieces as CommonJS. You pick one, and you make sure that Node understands how it should interpret your code.


Top comments (1)

benayat profile image

option num.2 with es6 still not working for me, did just like you did.
still getting the error: "Error: Cannot find module 'C:\Users\benay\Google Drive\appleseeds\backend\exercises\index.js"
did you bump into this too? any idea?