'How to use normal imports and top-level await at the same time?
I want to use imports (import x from y
) and top-level awaits at the same time with ts-node. However if I change my tsconfig.compilerOptions.module
to es2017
or higher as required by top-level awaits I get:
SyntaxError: Cannot use import statement outside a module
The fix for this is according to countless GH issues and SO questions to set tsconfig.compilerOptions.module
to commonjs
which in turn results in:
Top-level 'await' expressions are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', or 'nodenext', and the 'target' option is set to 'es2017' or higher
How can I have both? There has to be a way...
tsconfig.json:
{
"compilerOptions": {
"declaration": true,
"module": "esnext",
"target": "es2017",
"moduleResolution": "node",
"esModuleInterop": true,
"noImplicitAny": true,
"removeComments": true,
"preserveConstEnums": true,
"sourceMap": true,
"outDir": "dist",
"skipLibCheck": true,
"resolveJsonModule": true
},
"include": ["src/**/*.ts"]
}
package.json:
{
"name": "x",
"version": "0.0.1",
"main": "main.js",
"type": "module",
...
}
I am using Node LTS (v16.14.2) and TypeScript 4.6.3.
Solution 1:[1]
You can resolve this by:
Add node --es-module-specifier-resolution=node
to your node command.
Full Command: node --es-module-specifier-resolution=node app.js
see more:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | leonheess |