How to use ES6 in NodeJS

WARNING: This post is out of date. This method shouldn't be used in production and if you're using Babel 6, this won't work at all.

TL;DR require('babel/register'); at app entry point.

The Backstory

While converting an app from Rails to Node, I searched for how to use ES6 in NodeJS. Some responses recommend using node --harmony, others recommend starting your script with babel-node, or precompiling your app. We'll look at all of those options below, but…

Someone in the IRC room #reactjs turned me on to babel/register. It hooks into all require calls to transpile your app at runtime, and lets you start your app with regular Node.

1. Install Babel

npm install --save babel  

Optional: If you want to use any of the command line options like babel-node, put node_modules in your $PATH. Add this line to your ~/.bashrc:

export PATH="./node_modules/.bin:$PATH"  

Then open a new shell or run source ~/.bashrc.


2. Add an Entry Point Script

Make a new JavaScript file which will be the entry point of your app, like index.js, with the contents:

require('babel/register');  
require('./your_application_file.js');  

You're done! Enjoy writing ES6 in Node.

Babel also comes with JSX transpiling built in(!). You don't need to do any additional steps to require() React JSX files.

Check out the documentation. It details some configuration options like folders to include/exclude. By default, node_modules are excluded.

Warnings and Considerations

The documentation is clear enough:

If you're writing an application, it's completely fine to use. If, however, you're writing a library then you should compile your library and depend on the babel-runtime.

Also, this will have a small one time performance hit on your application:

…it uses a cache so you'll only get a small performance hit on first load https://twitter.com/sebmck/status/605751477374722048

I haven't personally noticed any speed differences on app startup.

Hopefully this tutorial will be obsolete when io.js is merged into NodeJS, adding the full ES6 feature set to Node core.

Other ES6 Options

The node --harmony flag runs your app with available ES6 features in node, but it's currently an extremely limited subset of the ES6 standard.

You can start your app with babel-node app.js, but under the hood this still uses the babel/register hook. The performance and output are the same. I prefer to keep my command line vanilla Node.

You can precompile your script with babel script --out-file built.js, then run node built.js. This may be ideal for deployed applications in performance heavy situations.

That's It!

This was inspired by my unexpectedly popular tweet. If this post helped you improve your ES6 prowess, consider following me on Twitter or buying me a coffee :).

comments powered by Disqus