Notes

ES6 (ES2015) and Beyond with Node.js

Edit on GitHub

JavaScript
2 minutes

tl;dr

 1# initialize
 2npm init -y
 3
 4# install dependencies
 5npm i -D babel-cli babel-preset-es2015 babel-preset-stage-0 nodemon
 6
 7# Babel config
 8touch .babelrc
 9echo '{ presets: [ "es2015", "stage-0" ] }' >> .babelrc
10
11# directory structure
12# mkdir src && touch src/index.js
13# add some es6 code to index.js for testing
14
15# run Babel
16babel-node src/index.js
17
18# add npm run scripts

Note: For the sake of simplicity, i use ES6 and ES2015 interchangeably. Both mean the same thing to me, though technically it should be called ES2015, that’s the official version name.

install dependencies

install Babel for code transpilation, a babel preset for ES2015, and nodemon for monitoring file changes

1npm i -D babel-cli babel-preset-es2015 nodemon

babel configuration

create a Babel configuration file called .babelrc, and add your presets to it

1nano .bablerc
1{
2  presets: [ "es2015" ]
3}

boilerplate code for testing

test with some ES2015 code

1// path: src/index.js
2import { createServer } from 'http' // ES6 named import instead of require()
3createServer((req, res) => { // ES6 arrow function
4  res.writeHead(200, { 'Content-Type': 'text/plain' })
5  res.end('Hello World \n')
6}).listen(3000, '127.0.0.1')
7
8console.log(`Server running at http://127.0.0.1:3000`)

run babel

You can either transpile directly with the command babel-node src/index.js or add an npm run script to run babel

1"scripts": {
2  "dev": "babel-node src/index.js"
3}
1npm run dev

bring in nodemon

1"scripts": {
2  "dev": "nodemon --exec babel-node src/index.js"
3}

Now nodemon will watch your files and if anything changes execute the babel-node command specified

Babel for production

The is all good for development. But babel-node isn’t meant to be used in production. We can add scripts though so it builds the code for production. The scripts will transpile our code and

1"scripts": {
2   "dev": "nodemon --exec babel-node src/index.js",
3   "prestart": "babel src --out-dir dist",
4   "start": "node dist/index.js"
5}

If we call our script prestart, npm will automatically run it every time we run start, it’ll run prestart first.

Also, add the dist directory to .gitignore so we are never checking in generated code, because we don’t need to.

1echo 'dist' >> .gitignore

We can watch the whole folder, like so:

1"dev": "NODE_ENV=development nodemon -w src --exec \"babel-node src --presets=es2015,stage-0\""

Related