< go back to home

How To Run ES6 Module In NodeJS

September 10, 2017

Most features in ECMAScript 2015 or ES6 can now be used in NodeJS for production. Unfortunately, ES6 Module which is one of my favorite new feature is not yet avaiable. A great article explaining the current state of ES6 Module in NodeJS is written here and I recommend it as a great read.

I've already written an article on how to use ES6 features in the browser which includess ES6 Modules. In NodeJS environment, you can theoretically also use ES6 module by tanspiling which generates file that is compatible to CommonJS module. I'm not using that though as it might not yet be ready for production.

However, there were times when I'm just experimenting, scripting or testing and I would prefer to use ES6 module. In such cases, I would just prefer to run the JS script file as it is and not generate a CommonJS compatible file. For that, I use "babel-node". Here's how I do it...

Install babel-cli and babel-presets-es2015 which are needed to be able to use ES6 module. Usually, we don't need this libraries in NodeJS for most ES6 features.

You may now use ES6 Module "import" and "export" keywords in a Javascript file using the following command:

Let's try that. Create two files name exporter.js and importer.js and copy the following codes...

Now, run the files using babel-node:

This verifies that we were able to use ES6 module directly in the script without having to transpile and generate a new file. A sample code implementation can be checked here at my github which I am using for experimenting. Interestingly, this is also applicable to MochaJS where you just replace babel-node with "./node_modules/.bin/mocha".

< go back to home