大家好。我正在学习打字稿。我读到了有关顶级等待的信息,我试图在节点应用程序中启用它,但它不起作用。互联网上没有任何明智的材料。请帮助。
我做了什么。
- npm 初始化
- npm i -D typescript @types/node ts-node
- 然后他安装了 Nodemon。
打字稿 - 5.3.3
我正在尝试在index.ts 中使用await。
- 他写信给我:“错误 TS1378:仅当 'module' 选项设置为 'es2022'、'esnext'、'system'、'node16' 或 'nodenext' 时才允许顶级 'await' 表达式,并且‘target’选项设置为‘es2017’或更高。”
- 在 tsconfig 中,我将目标更改为 es2022,模块更改为 node16。
- 它开始写“当前文件是 CommonJS 模块,不能在顶层使用‘await’”
- 我正在尝试将 type: module 插入 package.json 中。
- 开始写入“未知文件扩展名“.ts”
然后我们就没有想法了。请帮我打败这个废话。
tsconfig.json
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
}
包.json
"name": "ts-top-await-template",
"version": "1.0.0",
"description": "",
"main": "index.ts",
"scripts": {
"dev": "nodemon index.ts",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [ ],
"author": "",
"license": "ISC",
"devDependencies": {
"@types/node": "^20.11.19",
"nodemon": "^3.0.3",
"ts-node": "^10.9.2",
"typescript": "^5.3.3"
}
我运行 npm run dev
看起来你和我一样都有Node 20版本。在这里找到了您问题的答案:
Github ts-node 问题:Node v20.0.0 上的 ERR_UNKNOWN_FILE_EXTENSION
简要摘录: ts-node 目前与 Node 20 存在兼容性问题。如果您想使用 ts-node 在 Node 20 上运行代码,则必须运行以下命令,这会导致我们无法获得错误发生时的详细堆栈跟踪:
因此,要使其正常工作
top-level await,您需要执行以下步骤:tsconfig.json以下选项(其余保持不变):package.json:"type": "module"devnpm run dev。例如,我将在这里留下我的测试
index.ts:执行结果: