Getting Started with ES6 for Node.js
I assume that you:
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: https://github.com/Andyccs/es6_getting_started
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:
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”.