babel 6 async / await: Unexpected token

前端 未结 5 2020
眼角桃花
眼角桃花 2021-02-07 09:33

Im having trouble getting async / await transforms working. What am I missing?

My .babelrc:

{
  \"presets\": [ \"es2015\", \"stage-0\" ]
}
相关标签:
5条回答
  • 2021-02-07 10:02

    According to this post you need to have babel-polyfill

    Babel 6 regeneratorRuntime is not defined with async/await

    Hopefully it'll help you :)

    EDIT:

    It doesn't have to be babel-polyfill but it's the only one I used.

    As Gothdo said: the await keyword has to be in a function scope. Moreover, this function definition has to have the async keyword.

    This means that you can not have the await keyword on the top-level scope.

    0 讨论(0)
  • 2021-02-07 10:04

    Looks like async/await is only available in babel-preset-stage-3

    http://babeljs.io/docs/plugins/preset-stage-3/

    0 讨论(0)
  • 2021-02-07 10:07

    You can compile them yourself using the transform-async-to-module-method plugin, this allows you to compile them down to bluebird co-routines which requires ES6 generators (available in node4).

    Or if you need to compile it back to ES5 so it's compatible for browsers you can use transform-async-to-generator and facebook's regenerator.

    I've written about how to set up your babel config here http://madole.xyz/async-await-es7/

    0 讨论(0)
  • 2021-02-07 10:15

    It's recommended to upgrade to Babel 7 and use babel-env as opposed to stages (see here: https://github.com/babel/babel-upgrade).

    There's a command you can use to upgrade accordingly:

    npx babel-upgrade
    
    0 讨论(0)
  • 2021-02-07 10:16

    Use the Async to generator transform.

    Installation

    $ npm install babel-plugin-transform-async-to-generator
    

    Usage

    Add the following line to your .babelrc file:

    {
      "plugins": ["transform-async-to-generator"]
    }
    
    0 讨论(0)
提交回复
热议问题