LoyalPotato
LoyalPotato

Reputation: 471

How to support top-level awaits in typescript?

I'm using version 4.3.5 of typescript with Ionic and have ts(1378) error.

Here are is the tsconfig:

{
  "compilerOptions": {
    "target": "es2017",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "sourceMap": true,
    "noImplicitAny": true,
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "ESNext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": [
    "src"
  ],
  "exclude": [
    "node_modules",
    "**/*.spec.ts"
  ]
}

And the code where I'm getting the error:

import { Storage } from '@ionic/storage';

const store = new Storage();
await store.create();

export default store;

According to the error all I needed to change was the target to >=es2017 and the module to esnext or system, but I have that and it still shows me the error.

Don't know if it's relevant but you can see my folder structure here.

Thanks in advance :)

Upvotes: 2

Views: 1866

Answers (1)

SamiElk
SamiElk

Reputation: 2382

The issue doesn't come from your tsconfig but from webpack.

Top level await is still an experimental feature in webpack. You would have to include experiments: { topLevelAwait: true } in your webpack.config to make it work.

https://webpack.js.org/configuration/experiments/

However create-react-app manages the webpackconfig files for you and you would have to eject from create-react-app to access them.

Ejecting from create-react-app is usually not recommended, especially to add an experimental feature. It could induce more issues than it resolves.

Here are the steps to follow if you still want to try:

npm run eject

add experiments: { topLevelAwait: true } in the return statement of the newly created config/webpack.config.js

To demonstrate that this is not a typescript compiler issue.

  1. Create a new project npm init
  2. Add only typescript to your project npm install typescript --save-dev
  3. Create your tsc.config file with the settings you want but with target es2017 or newer and module esnext or system.
  4. Create 1 file with top level await.
  5. Compile with npx tsc.
  6. Everything works.

Here is the ts.config I used for reference:

{
    "compilerOptions": {
        "target": "es2017",
        "module": "system"
    },
    "include": ["topLevelAwait.ts"]
}

Upvotes: 2

Related Questions