简体   繁体   中英

How to use webpack to transform the await keyword to es5?

I can't for the life of me figure out how to transform code using await to valid es5. I'm using webpack 3 and can successfully transform async functions to functions returning promises, but its erroring on await : Module build failed: SyntaxError: ...: await is a reserved word . I assumed I needed a particular babel-loader plugin, but I don't see one for await . Here's the relevant part of my webpack config:

     module: {   
        rules: [{
          test: /\.js$/,
          exclude: /(node_modules|bower_components)/,
          use: {
            loader: 'babel-loader',
            options: {
              presets: ['es2015', 'stage-0'],
              plugins: ["syntax-async-functions","transform-regenerator"],
            }
          }
        }
      ]
    }

Is what I'm trying to do possible?

UPDATE:

Here's the relevant part of my webpack config now:

    module: {
        rules: [
        {
          test: /\.js$/,
          exclude: /(node_modules|bower_components)/,
          use: [{
            loader: 'nodent-loader',
            options: {
              promises: true,
              wrapAwait: true
            }
           },
           {
            loader: 'babel-loader',
            options: {
              presets: ['es2015', 'stage-0'],
              plugins: ["syntax-async-functions","transform-regenerator"],
            }
           }
          ]
        }
      ]
    }

And here's the code I'm trying to compile:

module.exports = async function() {
    var x = await wait()
}

async function wait() {
    return new Promise(function(resolve) {
        setTimeout(function() {
            resolve()
        },1000)
    })
}

You actually have async declared on the wrong function.

your wait function is not async. You call it, and it immediately returns a promise.

you need add async to this.init , which IS an async function. It doesn't return right away because it needs to await the promise to resolve.

See docs for reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM