How to use ES6 in NodeJS
require('babel-register'); at app entry point.
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 Register
npm install --save babel-register
Optional: If you want to use any of the command line options like
node_modules in your
$PATH. Add this line to your
Then open a new shell or run
2. Add an Entry Point Script
index.js, with the contents:
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
This may 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.
It probably shouldn't be used in production but information around this frequently changes.
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
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.
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 :).