【问题标题】:topLevelAwait invalid with babel-loader: 'await' is only allowed within async functionstopLevelAwait 对 babel-loader 无效:“await”只允许在异步函数中使用
【发布时间】:2020-11-13 05:08:16
【问题描述】:

webpack5 支持 topLevelAwait,只需添加以下选项:

//webpack.config.js

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

现在我们可以愉快地使用顶级等待了,像这样:

import Test from './Test';

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

效果很好。

但是当我添加 babel-loader 时它不起作用:

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

它会抛出一个错误:

'await' is only allowed within async functions

我该如何解决这个问题?

我需要 topLevelAwait 和 babel-loader。

【问题讨论】:

    标签: webpack babeljs babel-loader webpack-5


    【解决方案1】:

    你需要开启 Babel 对顶层 await 的解析,即使 Webpack 本身支持它,因为 Babel 必须在 Webpack 之前解析文件很久。

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

    然后将其添加到您的 Babel 配置或 Webpack 配置中,例如

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

    【讨论】:

    • 请注意,您的配置中需要experiments: { topLevelAwait: true },以及作为插件。
    猜你喜欢
    • 2018-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-26
    • 2022-06-18
    • 2020-09-07
    • 2019-09-12
    • 1970-01-01
    相关资源
    最近更新 更多