Gettings started with Babel and Node

I've been using Babel recently to perform transpiling of Node.js code. I've previously used Traceur and it always left a bit to be desired. The big winner now, is the support of ES7 code such as async/await.

This guide will show a few examples of how you can use Babel to transpile ES6/7 code.

Command Line

The easiest way to transpile your code, is to not bother! When babel is installed via npm install -g babel it will add the command line utility babel-node.

This lovely little tool will perform autmatic transpiling for you. No need for build steps or complicated code. Lets take for example this code in a file called test.js

let vals = [1,2,3,4,5];  
vals.forEach((val) => console.log(val));  

Attempting to run node test.js will throw an error (the error depends on which version of Node.js you have installed. In order for this code to work, you can simply run:

babel-node test.js  

More info https://babeljs.io/docs/usage/cli/

Require Hook

Another technique to get things to work without a build step is to use a Require Hook. We can register Babel, which will hook into the require and automatically transpile our code for us!

There are some caveats that you can read about here https://babeljs.io/docs/usage/require/. Mostly, it's that you can't use these for dependency libraries. But it does work for your applications.

To get this to work, you create a bootstrapper file that registers Babel and then loads your module. Lets call it bootstrap.js

// bootstrap Require Hook transpiling
require('babel/register');

// now load our app entry point
require('./test');  

You can then run Node as you normally would and it will launch your application with transpiling.

node bootstrap.js  

Precompiling

The more heavyweight option is to precompile your code. This is great for code that is going to be deployed or referenced in other apps, such as a library. It is also much faster during application startup as you don't need to transpile the entire dependency chain. Another benefit is that you can generate map files for debugging.

If you're using grunt-babel or gulp-babel it will transpile your code for you.

To do it directly you can run the following command line arguments:

babel test.js -o dist/test.js  

Then you can call your transpiled code:

node dist/test.js  

Async/Await

To get Async/Await working, you will need to set the es7.asyncFunctions optional value.

It is also recommended that you include the babel-runtime package with

npm install babel-runtime --save  

Then include that in your options as well to use the runtime to add the regenerator polyfill.

To see an example of this in action checkout: https://github.com/bmancini55/babel-async-test

comments powered by Disqus