如何使用顶级“等待"?在打字稿 next.js [英] how can I use top level "await" in typescript next.js
问题描述
当我使用等待"时像这样在顶层:
When I use "await" on top-level like this:
const LuckyDrawInstance=await new web3.eth.Contract(abi)
我在终端上收到警告:set Experiments.topLevelAwait true".当我尝试将其添加到tsconfig.json"时,它仍然不起作用.它说实验";属性不存在.
I got a warning on the terminal: "set experiments.topLevelAwait true". When I tried to add this to "tsconfig.json", it still does not work. it says "experiments" property does not exist.
我可以将它包装在一个异步函数中,但我想在没有包装函数的情况下设置它.
I could wrap it inside an async function but I want to set it without a wrapped function.
推荐答案
与tsconfig.json无关.你必须在 next.config.js 中设置它.新版 next.js 使用 webpack5,webpack5 支持顶层 await.
It is nothing to do with the tsconfig.json. You have to set it inside next.config.js. New version of next.js uses webpack5 and webpack5 supports top level await.
module.exports = {
webpack: (config) => {
config.experiments = { topLevelAwait: true };
return config;
},
};
注意
你必须在功能组件之外使用它:
You have to use it outside the functional component:
export default function Navbar() {
// this will throw error
// Syntax error: Unexpected reserved word 'await'.
const provider=await customFunction()
return (
<section>
</section>
);
}
警告
由于它是实验性的,它可能会在某些版本中被破坏
Warning
Since it is experimental, it might be broken in some versions
这篇关于如何使用顶级“等待"?在打字稿 next.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!