How to use top-level "await" in TypeScript Next.js
P粉200138510
P粉200138510 2023-10-22 12:36:52
0
2
709

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.

P粉200138510
P粉200138510

reply all(2)
P粉262926195

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 topLevelAwait via . swcrc file.

  1. Add the Babel plugin named @babel/plugin-syntax-top-level-await to package.json.

For example.

{
    "devDependencies": {
        "@babel/plugin-syntax-top-level-await": "^7.14.5"
    }
}
  1. Create the .babelrc file in the root directory of the project where package.json is located.

  2. Make sure to include the next/babel preset and the topLevelAwait plugin 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.

P粉541551230

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 webpack5 feature, 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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template