Getting Started with ES6 for Node.js

While I were busy with my internship project over the last 3 months, ECMAScript 6 (ES6) has been officially published on June 2015. This standard bring javascript to a whole new level with new features like classes, import/export statements, etc. Here is a list of new feature in ES6:

While most browsers are still not compatible with this version of javascript, there are various transpiler (transformer and compiler) such as babel can let you write and run your ES6 program.

Most of us will not migrate to ES6 in near future. I guess most likely ES6 and older standard would live together in the future, but ES6 is really an exciting progress for javascript.

Like most developers, I want to get started with ES6. ES6 is still new at the time of writing and it is build on top of older javascript. You can’t find much references to get started. I’m writing this article so that Node developers can get started with ES6.

Note: I found several laundry lists for ES6 such as this and this.


I assume that you:

  1. know Node.js
  2. know Grunt
  3. know how to use terminal / cmd

Getting Started

In this demo, I’m gonna to show you “classes” and “export/import modules” features in ES6. We will create a class called Rectangle and import this class in another file and use it there. I have created a repo in Github for this demo:

Let’s create a new folder somewhere in your computer and called it “es6_first_try”. The folder structure should look like this:

Open up your rectangle.js file in src folder. Here is the fun part, we create a class called Rectangle:

Did you see that? The class, constructor, set and get keywords! Finally we can write something similar to an object-oriented language in javascript! You should also take note that there is an “export” keyword at the beginning. This keyword actually will be transformed to “exports.Rectangle = Rectangle;” in the real code.

Open up your app.js file in src folder. In this file, we will import Rectangle class and use it.

At line 1, we’re saying “import Rectangle class from rectangle.js file”. Super intuitive, isn’t it? As most of you might guess, the output of this program should be “true”.

Now we need to run these codes, but Node.js does not know ES6 yet! So we need a transpiler to transform our code to ES5, specifically, we are going to use babel to do it. In our Gruntfile.js, we will define a babel task that will transform ES6 files to ES5 files and put them in a folder called dist.

Please help yourself to copy the content of package.json. Since you’re a great Node.js developer, you should know what is this file about.

Next, make sure you get all dependencies by running “npm install” and transform your ES6 code to ES5 by running “grunt babel”. You should get a new folder called “dist” with tranformed codes in that folder.

Finally, you should be able to run your code by using the command “node dist/app.js” and get a single line result “true”.