Start Writing ES6 JavaScript in your Node.js Apps Today!

ECMAScript 6 (the next version of JavaScript) should be rolling out in browsers sometime this year. If you want to start using the awesome features of ES6 now you have a couple of choices:

  1. Use the Node.js Harmony flag ala node --harmony app.js to enable the new ES6 features in the language.
  2. Run io.js which includes all stable ES6 features by default.
  3. Write your code using ES6 and transpile it to ES5 using something like Babel (formerly 6to5) or Traceur.

If you are like me and want to dip our toes into the ES6 water instead of making the plunge, heres how you can build a simple Express app with parts of it, lets say your modules, written using ES6 and then transpile them to ES5 like the rest of your code.

The most popular transpiler right now is Babel. It does a really good job of generating vanilla ES5 JavaScript, supports a multitude of browsers and has great docs! You can use the require hook (e.g., require("babel/register")) to transpile your code at runtime but I prefer to deploy transpiled code instead. If you are using something like grunt, gulp, brocolli or [insert JS communitys build tool of the day], there are plugins to transpile your code as part of your current workflow. Were going to use the (simple) Babel CLI to transpile our code.

First thing well do is use the Express Generator to scaffold a basic app for us.

express my-es6-app

Now create the source file for your ES6 code. This is the module well write that will be transpiled to ES5.

mkdir lib
mkdir lib/src
touch lib/src/greet.es6

The code for our ES6 module (lib/src/greet.es6) is ridiculously simple.

export default class Greeter {
 constructor(name) {
  this.name = name;
 }
 sayHello() {
  return "Hello " + this.name;
 }
}

Now that we have our ES6 code in place well need to install Babel and have it perform the work on transpiling it.

npm install --global babel

There many ways to transpile your code but I like to set up a watch so that whenever my code changes it is automatically compiled into the correct file structure.

babel lib/src/greet.es6 --out-file lib/greet.js --watch

So now were all set. Weve written our ES6 code and used Babel to transpile it into vanilla ES5. All we need to do now is use it in our application. So lets add it to the route for our home page in /routes/index.js.

var express = require('express');
var router = express.Router();
// require our module
var Greeter = require("../lib/greet.js");
// call the sayHello function
var greeting = new Greeter('Jeff').sayHello();

/* GET home page. */
router.get('/', function(req, res) {
 // display the greetings as the title of the app
 res.render('index', { title: greeting });
});

module.exports = router;

So now you have a simple way to use ES6 features in your ES5 app today!!