To actually use top level await (i.e. without wrappers)
I'm going to describe the cause and solution to your problem with tsc, but also show you a much better way to run .ts files from the command line.
Here's something you may have missed:
tsc ignores the configuration in tsconfig.json when provided with a file name to compile.
It's also mentioned in --help but I do agree it's a bit unintuitive:
$ npx tsc --help tsc: The TypeScript Compiler - Version 4.6.2 TS COMMON COMMANDS .... tsc app.ts util.ts Ignoring tsconfig.json, compiles the specified files with default compiler options.
Solution 1 - specify a ts file explicitly and use command line args to provide the right options:
So you'll need to use:
npx tsc -t es2022 -m es2022 --moduleResolution node --outDir dist src/runme.mts
Solution 2 - use tsc specifying the .ts file using src in tsconfig.json
Here's a config with the correct settings for top level await:
{ // https://www.typescriptlang.org/tsconfig#compilerOptions "compilerOptions": { "esModuleInterop": true, "lib": ["es2020"], "module": "es2022", "preserveConstEnums": true, "moduleResolution": "node", "strict": true, "sourceMap": true, "target": "es2022", "types": ["node"], "outDir": "dist" }, "include": ["src/**/*"], "exclude": ["node_modules"] }
Make sure the include folders in your tsconfig.json contain your typescript that uses top level await:
npx tsc
dist/runme.mjs is generated and my compiled app runs.
Solution 3: use a better tool like tsx
tsx is a newer tool than just runs ts files with minimal prior setup. Unlike tsc, ts-node etc, tsx:
- Does not need a
tsconfig.json - Supports top level
await - Is not deprecated like
esrun - Does not give silly error messages (like ts-node saying
[ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for file.ts when running TS files is literally ts-node's only job)
1. Ensure you have type: "module" in package.json.
2. Install tsx
npm i tsx
3. Use tsx
Then just:
npx tsx file.ts
No other setup is needed.
tscignores yourtsconfig.jsonif you pass files explicitly.tsconfig.jsonoptions are correct.