Search code examples
webpackbabeljsbabel-loaderwebpack-5

topLevelAwait invalid with babel-loader: 'await' is only allowed within async functions


webpack5 supports topLevelAwait, just add the following options:

//webpack.config.js

module.exports = {
  //...
  experiments: {
    topLevelAwait: true
  },
};

Now we can use top level await happily, like this:

import Test from './Test';

const _Test = await import("./Test");
console.log(_Test);

It works well.

But when I add babel-loader it will not work:

module.exports = {
  //...
  experiments: {
    topLevelAwait: true
  },
  module:{
    rules:[
      {
        test: /\.(js|mjs|jsx|ts|tsx)$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader'
        }
      }
    ]
  },
};

It throws an error:

'await' is only allowed within async functions

How can I solve this problem?

I need topLevelAwait and babel-loader.


Solution

  • You need to enable Babel's parsing of top-level await, even if Webpack itself supports it, because Babel has to parse the file long before Webpack does.

    npm install --save-dev @babel/plugin-syntax-top-level-await
    

    then add it to your Babel config or Webpack config, e.g.

      {
        test: /\.(js|mjs|jsx|ts|tsx)$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            plugins: ['@babel/plugin-syntax-top-level-await'],
          }
        }
      }