When I use "await" at the top level like this:
const LuckyDrawInstance=await new web3.eth.Contract(abi)
I get the warning on the terminal: "set Experiments.topLevelAwait true". When I try to add it to "tsconfig.json" it still doesn't work. It says the "experimental" property does not exist.
I can wrap it in an async function, but I want to set it without the wrapping function.
The latest solution that worked for me at the time of writing this article is to use Babel instead of SWC, because Next.js does not allow custom SWC configuration, therefore, you cannot allow
topLevelAwaitfile.via. swcrc@babel/plugin-syntax-top-level-awaittopackage.json.For example.
{ "devDependencies": { "@babel/plugin-syntax-top-level-await": "^7.14.5" } }Create the
.babelrcfile in the root directory of the project wherepackage.jsonis located.Make sure to include the
next/babelpreset and thetopLevelAwaitplugin in.babelrc.For example.
{ "presets": ["next/babel"], "plugins": [ "@babel/plugin-syntax-top-level-await" ] }This was the simplest solution until the Next.js team allowed us to include SWC configuration. Note that by doing this you will not get the performance benefits of SWC as it will be disabled in favor of Babel.
Has nothing to do with tsconfig.json. You must set it in next.config.js. The new version of next.js uses webpack5, which supports top-level await.
module.exports = { webpack: (config) => { // this will override the experiments config.experiments = { ...config.experiments, topLevelAwait: true }; // this will just update topLevelAwait property of config.experiments // config.experiments.topLevelAwait = true return config; }, };Notice
You must use it outside of a functional component:
export default function Navbar() { // this will throw error // Syntax error: Unexpected reserved word 'await'. const provider=await customFunction() return ( <section> </section> ); }Next 13 items
The same settings apply to "next" in the "pages" and "app" directories: "^13.1.6" . (Because this feature is a
webpack5feature, not a next.js feature) You can test it using the following sample code:const _promise = async () => { return new Promise((resolve, reject) => resolve(4)); }; // you might get typecsript warning const val = await _promise(); console.log("val", val);warn
Since it is experimental, it may be broken in some versions