Categories
Javascript NodeJS

Using ES7 async/await today with Babel

Let’s take a code snippet that contains the demonstration of async/await — https://gist.github.com/patrickarlt/8c56a789e5f185eb9722 – our objective is to transpile this piece of code to ES5 (current day Javascript) so we can run it with today’s version of NodeJS.

You will notice a command on top of the snippet which no longer works because Babel JS has changed. I am going to describe how we can do it with the latest version of babel as of this writing (6.1.4 (babel-core 6.1.4)).

Install Babel and Plugins

The new Babel depends on individual plugins to transform and parse codes. To transform async functions, we shall use the transform-regenerator plugin. We also need to add the syntax plugin to recognize the async/await syntax. Otherwise Babel won’t recognize those. Apart from that, we also install the ES2015 preset which includes a sane set of plugins for transforming ES6 to ES5. We will keep those so we can use other ES6 goodies.

First we install babel-cli globally:

Here’s our package.json file so you can just do npm install:

Configuring Babel

Here’s the .babelrc file I put in the same directory:

The file tells babel how to transform your code.

Transpile & Run

Once we have installed the dependencies, we can then start transpiling the codes to JS:

You might run into a problem like this:

It’s because we need to include the regenerator run time. The runtime is packed in the babel-polyfill we have already installed. We just need to include it in our source code. So the final github.es6 file would look like this:

Now if we transpile and run again, it should work fine.