如何在打字稿 next.js 中使用顶级“await”

Yil*_*maz 16 javascript typescript reactjs webpack next.js

当我在顶层使用“await”时,如下所示:

 const LuckyDrawInstance=await new web3.eth.Contract(abi)
Run Code Online (Sandbox Code Playgroud)

我在终端上收到警告:“设置experiments.topLevelAwait true”。当我尝试将其添加到“tsconfig.json”时,它仍然不起作用。它说“实验”财产不存在。

我可以将它包装在异步函数中,但我想在没有包装函数的情况下设置它。

Yil*_*maz 41

它与 tsconfig.json 无关。您必须在 next.config.js 中设置它。新版本的next.js使用webpack5,webpack5支持顶级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;
  },
};
Run Code Online (Sandbox Code Playgroud)

笔记

您必须在功能组件之外使用它:

export default function Navbar() {
  // this will throw error
  // Syntax error: Unexpected reserved word 'await'.
  const provider=await customFunction()

  return (
    <section>          
    </section>
  );
}
Run Code Online (Sandbox Code Playgroud)

下一页 13

相同的设置适用于"next": "^13.1.6"“pages”和“app”目录中。(因为此功能是一个webpack5功能,而不是 next.js 功能)您可以使用以下示例代码对其进行测试:

const _promise = async () => {
  return new Promise((resolve, reject) => resolve(4));
};
// you might get typecsript warning
const val = await _promise();
console.log("val", val);
Run Code Online (Sandbox Code Playgroud)

警告

由于它是实验性的,因此在某些版本中可能会被破坏

  • 这会将 config.experiments 中的对象替换为给定的对象。所有其他配置选项都将被擦除。只需 config.experiments.topLevelAwait = true 即可。+1 仍然解决了问题 (3认同)
  • 在 nextjs 13 中,这不再起作用。 (3认同)