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 esrun
esrun
is a newer tool than just runs ts
files with no prior setup. Unlike tsc
, ts-node
, tsx
etc, esrun:
- Does not need a
tsconfig.json
- Does not need
package.json
- Supports top level
await
- Does not give silly error messages (like ts-node saying it doesn't support running ts files)
npm i esrun
Then just:
npx esrun file.ts
No other setup is needed.
tsc
ignores yourtsconfig.json
if you pass files explicitly. – Flamboyanttsconfig.json
options are correct. – Indemnify