Using ECMAScript 6 in Node.js

ECMAScript 6, the long awaited next iteration of the JavaScript language get’s more and more browser support lately. Also in io.js a lot of the new features are supported. But Node.js is still lacking most of the features.

Google build Traceur, a compiler from ES6 to old JavaScript. To use this as a drop-in in Node.js, just install traceur-runner:

npm install traceur-runner --save

Then require it in the entry point of your project:

require('traceur-runner');

It will then convert ES6 syntax on the fly to Node.js compatible old JavaScript. Hurray for arrow functions, classes, imports and so on!


Update 2015/03/10:

When building a module for npm, using traceur-runner doesn’t work. But I found another solution: babel.

Install it as a development dependency:

npm install babel --save-dev

Instead of converting the files on the fly as traceur-runner does, we have to choices: Run the script with babel-node instead of node or add a build step with babel.

For geobatch, a batch geocoder for the Google Maps API, I use babel. The package.json contains the important things:

{
  …
  "main": "dist",
  scripts: {
    "prepublish": "./node_modules/.bin/babel src --out-dir dist",
    "test": "./node_modules/.bin/babel-node ./node_modules/.bin/_mocha test",
    …
  }
  …
}

So when running the tests, the source files are converted on the fly. Before publishing to the npm registry, the files are converted to plain old JavaScript syntax.

It’s a bit more hassle than I’d liked to have, but once setup, the process works just fine.