我想与 ts-node 同时使用导入(
import x from y
)和顶级等待。但是,如果我按照顶级等待的要求将我的 tsconfig.compilerOptions.module
更改为 es2017
或更高,我会得到:
SyntaxError: Cannot use import statement outside a module
解决此问题的方法是根据无数的 GH 问题和 SO 问题将
tsconfig.compilerOptions.module
设置为 commonjs
,这又会导致:
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
我怎样才能两者兼得?一定有办法...
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",
...
}
我正在使用 Node LTS (v16.14.2) 和 TypeScript 4.6.3。
根据您的评论,这个答案与
ts-node
无关,只涉及Node.js和TypeScript。
鉴于以下项目:
.
├── src/
│ ├── file.ts
│ └── main.ts
├── package.json
└── tsconfig.json
package.json
"type": "module"
tsconfig.json
{
"compilerOptions": {
"target": "ESNext",
"module": "NodeNext",
"moduleResolution": "Nodenext",
"outDir": "dist"
},
"include": ["src"]
}
src/y.ts
const doSomethingAsync = () => Promise.resolve('something async')
export { doSomethingAsync }
export default 'y'
src/main.ts
import { doSomethingAsync } from './file.js'
import x from './file.js'
console.log(await doSomethingAsync())
console.log(x)
现在运行
./node_modules/.bin/tsc
以在 dist/
中生成构建。
现在运行
node dist/main.js
:
something async
y
使用了以下版本的 Node.js 和 TypeScript:
如果您需要使用
ts-node
我可以进一步深入,但您并没有真正解释为什么需要该工具。另外,如果您出于某种原因想直接执行 tsx
文件,我会考虑 ts-node
而不是 .ts
。
使用
[email protected]
,您可以通过运行获得相同的输出:
./node_modules/.bin/tsx src/main.ts