13

I would like to have top level await in my typescript nodejs project.

My tsconfig used to look like this:

{
  "compilerOptions": {
    "target": "es2017",
    "module": "commonjs",
    "lib": [
      "dom",
      "es6",
      "es2017",
      "esnext.asynciterable"
    ],
    "skipLibCheck": true,
    "sourceMap": true,
    "outDir": "./dist",
    "moduleResolution": "node",
#### other stuff which I think is not relevant removed ####

And I now switched it to

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "lib": [
      "dom",
      "es6",
      "es2017",
      "esnext.asynciterable"
    ],
    "skipLibCheck": true,
    "sourceMap": true,
    "outDir": "./dist",
    "moduleResolution": "node",
#### other stuff which I think is not relevant removed ####

I have also added "type": "module" to my package.json. Indeed I now have the ability to do top level awaits however

  1. I need to change every import to add the .js file extension
  2. For folders where I added an index.ts to export all the modules I could previously just import the folder name. Now I need to import foldername/index.js
  3. When I auto add an import with vscode it adds it without the .js

The way it is with commonjs is so elegant - can I have the same behaviour with esnext or keep it some other way while gaining top-level await?

sev
  • 1,500
  • 17
  • 45

2 Answers2

0

Here's an example of what your tsconfig.json file might look like:

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "lib": [
      "dom",
      "es6",
      "es2017",
      "esnext.asynciterable"
    ],
    "skipLibCheck": true,
    "sourceMap": true,
    "outDir": "./dist",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "esModuleInterop": true
    },
  }
0

I don't know if that is an option, but i think the easiest approach would be, to wrap the entrance of your application into some kind of main() function that is async and execute that function. Inside this function, you can use await like you want.

Woodpecker
  • 31
  • 2