【问题标题】:how can I use top level "await" in typescript next.js如何在 typescript next.js 中使用顶级“等待”
【发布时间】:2021-09-21 03:22:27
【问题描述】:

当我像这样在顶层使用“等待”时:

 const LuckyDrawInstance=await new web3.eth.Contract(abi)

我在终端上收到一条警告:“set Experiments.topLevelAwait true”。当我尝试将此添加到“tsconfig.json”时,它仍然无法正常工作。它说“实验”属性不存在。

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

【问题讨论】:

    标签: javascript typescript webpack async-await next.js


    【解决方案1】:

    与 tsconfig.json 无关。你必须在 next.config.js 中设置它。新版 next.js 使用 webpack5,webpack5 支持顶层 await。

    module.exports = {
      webpack: (config) => {
        config.experiments = { topLevelAwait: true };
        return config;
      },
    };
    

    注意

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

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

    警告

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

    【讨论】:

      【解决方案2】:

      我已经为此苦苦挣扎了 2-3 天。这是一个有效的解决方案。请按照以下步骤操作。

      1.将以下内容复制粘贴到您的 package.json 中

      {
        "name": "projectname",
        "version": "1.0.0",
        "description": "",
        "main": "index.js",
        "scripts": {
          "test": "mocha",
          "dev": "next dev"
        },
        "author": "",
        "license": "ISC",
        "dependencies": {
          "@truffle/hdwallet-provider": "^2.0.1",
          "fs-extra": "^10.0.0",
          "ganache-cli": "^6.12.2",
          "mocha": "^9.1.4",
          "next": "^12.0.8",
          "react": "^17.0.2",
          "react-dom": "^17.0.2",
          "solc": "^0.8.9",
          "web3": "^1.7.0",
          "@babel/plugin-syntax-top-level-await": "^7.14.5"
        },
        "devDependencies": {
          "@babel/plugin-syntax-top-level-await": "^7.14.5"
        }
      }
      

      2。删除您的 node_modules 文件夹

      3.转到项目的根目录并使用npm install 命令重新安装所有包

      4.在项目的根目录中创建一个新文件并将其命名为"next.config.js"

      5.将以下代码复制粘贴到next.config.js 文件中并保存。

      module.exports = {
        // target: 'experimental-serverless-trace',
        webpack: (config) => {
          config.experiments = config.experiments || {};
          config.experiments.topLevelAwait = true;
          return config;
        },
      };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-02-13
        • 2023-03-05
        • 1970-01-01
        • 2022-09-28
        • 2021-09-27
        • 2019-07-17
        • 2021-03-26
        相关资源
        最近更新 更多