28

Facing Below build issue:

Module parse failed: The top-level-await experiment is not enabled (set experiments.topLevelAwait: true to enabled it)

File was processed with these loaders:
 * ./node_modules/babel-loader/lib/index.js
 * ./node_modules/source-map-loader/dist/cjs.js
You may need an additional loader to handle the result of these loaders.
Error: The top-level-await experiment is not enabled (set experiments.topLevelAwait: true to enabled it)

Any please provide some solution for this ?

snoob dogg
  • 2,491
  • 3
  • 31
  • 54

5 Answers5

27

I got this error when exporting a module with async. Just add this to the module.exports object in webpack.config.js file.

experiments: {
  topLevelAwait: true
}

You can also read up about the experiment option in Webpack documentation. https://webpack.js.org/configuration/experiments/

Yoav Kadosh
  • 4,807
  • 4
  • 39
  • 56
Bello Tomi
  • 513
  • 6
  • 9
16

Here's a workaround for those coming from Next.js source

/** @type {import("next").NextConfig} */
module.exports = {
  experimental: { appDir: true },
  webpack(config) {
    config.experiments = { ...config.experiments, topLevelAwait: true }
    return config
  },
}
atasoyh
  • 3,045
  • 6
  • 31
  • 57
igmrrf
  • 459
  • 4
  • 11
  • A question though, what does this do and what side effects does it have? – kotAPI Mar 11 '23 at 05:57
  • a module can include an await in the code that executes at startup by factoring that code into an async function. – igmrrf May 04 '23 at 18:13
4

You can enable it in your webpack config.

If you created your react app with npx create-react-app my-app you have to install CRACO to override your webpack config.

After installation set topLevelAwait to true in your craco.config.js:

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

Run npm start and the error is gone.

1

Symfony

For anyone else trying to add this to the webpack.config.js generated by symfony, you can use the following syntax:

// Default config above...

const config = Encore.getWebpackConfig();

config.experiments = {
  topLevelAwait: true,
}

module.exports = config;
Michel Rummens
  • 459
  • 3
  • 9
1

Starting from webpack version 5.83.0, this feature [experiments.topLevelAwait] is enabled by default. (see https://webpack.js.org/configuration/experiments/#experimentstoplevelawait)

So as alternative to the experiments option, you can upgrade webpack. I had to eject my react app to upgrade. (What does this "react-scripts eject" command do?)

David
  • 355
  • 1
  • 9