当前位置: 代码迷 >> 综合 >> USING ES7 ASYNC/AWAIT TODAY WITH BABEL
  详细解决方案

USING ES7 ASYNC/AWAIT TODAY WITH BABEL

热度:55   发布时间:2024-01-10 01:09:47.0

http://masnun.com/2015/11/11/using-es7-asyncawait-today-with-babel.html

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-polyfillwe 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.


  相关解决方案