'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)
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.
Solution 1:[1]
I have been struggling with this for 2-3 days. Here is a solution that works. Please follow the following steps.
1. Copy paste the following in your 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. Delete your node_modules folder
3. Goto your project's root directory and reinstall all the packages using npm install command
4. Create a new file in your project's root directory and call it "next.config.js"
5. Copy paste following code in next.config.js file and save.
module.exports = { // target: 'experimental-serverless-trace', webpack: (config) => { config.experiments = config.experiments || {}; config.experiments.topLevelAwait = true; return config; }, };
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | GKV |

