Using Node with ES6 and beyond

JavaScript 2015/es6/2017 introduces a lot of new features but unfortunately not yet available in the current modern browsers. The latest Node versions have a pretty good support for ES6 out of the box. This blog post will describe all what you need to let you run your ES6 code on any kind of platform.

Start your project

$ mkdir es6-example
$ cd es6-example
$ npm init -y
Wrote to /Users/kimus/Develop/zlabs/es6-example/package.json:
{
"name": "es6-example",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "...",
"license": "ISC"
}

Add default development dependencies

$ npm i -D babel-cli babel-preset-es2015 nodemon
I recommend to install also nodemon to automatically reload your project on every source change.

Create starting files

Add Babel presets

Create .babelrc file:

{
"presets": ["es2015"]
}

Create index.js file:

import http from 'http';
// The handler argument is automatically
// set as a listener for the 'connection' event
const server = http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
});
// Listen on port 3000, IP defaults to 127.0.0.1
server.listen(3000);
// Put a friendly message on the terminal
console.log('Server running at http://127.0.0.1:3000/');

Change scripts in package.json

{
"name": "es6-example",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "nodemon -w src --exec babel-node src/index.js",
"prestart": "babel src --out-dir dist",
"start": "node dist/index.js"
},
"keywords": [],
"author": "...",
"license": "ISC",
"devDependencies": {
"babel-cli": "^6.23.0",
"babel-preset-es2015": "^6.22.0",
"nodemon": "^1.11.0"
}
}

Ignore dist folder

If you are using git, or other similar tool, you should ignore the dist folder.

$ echo "dist" >.gitignore

Run your project

Development

$ npm run dev
> es6-example@1.0.0 dev /Users/kimus/Develop/zlabs/es6-example
> nodemon -w src --exec babel-node src/index.js
[nodemon] 1.11.0
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: /Users/kimus/Develop/zlabs/es6-example/src/**/*
[nodemon] starting `babel-node src/index.js`
Server running at http://127.0.0.1:3000/

Production

$ npm start
> es6-example@1.0.0 prestart /Users/kimus/Develop/zlabs/es6-example
> babel src --out-dir dist
src/index.js -> dist/index.js
> es6-example@1.0.0 start /Users/kimus/Develop/zlabs/es6-example
> node dist/index.js
Server running at http://127.0.0.1:3000/
One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.