Writing ES6 in your Node.js Applications

ES6 (ECMAScript 2015) is the latest stable version of JavaScript. It includes new language syntaxes and implementations for the language. Three years later implementation of these new features in JavaScript engines is still ongoing but you’d still like to write your code in ES6 because who wants to stay behind in this industry.

We’d be using Babel here to convert our ES6 code that can be understood by the existing Javascript engines. Babel is a compiler that allows us to write ES6 features in JavaScript and run it in the older/existing engines.

How to set up Babel with your Node.js App

  1. You should have the latest node.js installed and running on your machine.
  2. Create a new project or run and move to this directory
$   mkdir new_project
$ cd new_project

3. Create a file app.js and write some ES6 code in there

import request from 'requests';
let helloWorld = 'Hello World!`;
console.log(`${helloWorld} this is some ES6 JavaScript code`);

4. Create a package.json file by running npm init . Enter the required details or press return for fields you do not recognise.
At this point your package.json should look like this

"name": "es6project",
"version": "1.0.0",
"description": "using babel with node",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"author": "",
"license": "ISC"

5. Install babel and babel preset as a dev dependency

$   npm install -D babel-cli
$ npm install -D babel-preset-es2015

6. Babel uses different plugins to enable different features. In our case we can use the es2015 plugin. We will need to create a .babelrc configuration file.

$   touch .babelrc

and paste the following in the file

"presets": ["es2015"]

7. Create an npm build command to compile your ES6 Javascript. Modify your package.json with

"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "babel --presets es2015 -d lib/ src"

this compiles all of your ES6 code in the src directory to the lib directory.

You should see your code compiled in the lib directory and now you are good to go and run this. This code is present in the this Github repository.

Like what you read? Give Dhruv Nenwani a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.