How to compile TypeScript to JavaScript with top-level await?

1.7k Views Asked by At

I would like to utilize top-level await available since TypeScript 3.8 in a NodeJS application.

So, the following TypeScript code:

import { getDoctorsPage } from "./utils/axios.provider";
const page = await getDoctorsPage("047", "1", "1");
console.log(page);

compiles to this JavaScript code:

import { getDoctorsPage } from "./utils/axios.provider";
const page = await getDoctorsPage("047", "1", "1");
console.log(page);
//# sourceMappingURL=index.js.map

And when I try to run it within WebStorm I get the following error:

(node:95053) ExperimentalWarning: The ESM module loader is experimental.
file:///Users/anatoly/Documents/git/maccabi-parser/dist/index.js:2
const page = await getDoctorsPage("047", "1", "1");
             ^^^^^

SyntaxError: Unexpected reserved word
    at Loader.moduleStrategy (internal/modules/esm/translators.js:81:18)
    at async link (internal/modules/esm/module_job.js:37:21)

Does the latest NodeJS 0.13.* support it?

My tsconfig.json

{
  "compilerOptions": {
    "target": "es2020",
    "module": "esnext",
    "pretty": true,
    "sourceMap": true,
    "outDir": "dist",
    "importHelpers": true,
    "strict": true,
    "moduleResolution": "node",
    "esModuleInterop": true,
    "rootDir": "src",
    "noImplicitAny": false,
    "strictNullChecks": false,
    "noImplicitThis": true,
    "alwaysStrict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": false,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "baseUrl": "./",
    "allowSyntheticDefaultImports": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "resolveJsonModule": true
  },
  "include": [
    "src/**/*"
  ],
  "exclude": [
    "node_modules",
    "dist"
  ]
}

and package.json contains "type": "module"

1

There are 1 best solutions below

0
On BEST ANSWER

As mentioned in the comments that this feature is not just dependent on the version of TS but more things like version of WebPack (if using WebPack) and existence of the V8 flag --js-flags="--harmony-top-level-await" during execution of the program or in configs.

Executing this code with this flag enabled can be done as mentioned in the comments:

node -r dotenv/config --harmony-top-level-await --es-module-specifier-resolution=node dist/index.js