TypeScript 顶级 await 错误解决方案
当使用 TypeScript 开发时,你可能会遇到以下错误:
Top-level 'await' expressions are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher.ts(1378)
这个错误表明你在顶层使用了 await
表达式,但 TypeScript 配置不支持这种用法。
问题原因
在 JavaScript 和 TypeScript 中,await
关键字通常只能在 async
函数内部使用。虽然 ES2022 规范引入了顶级 await 支持,但需要正确的编译配置才能使用此功能。
解决方案
方案一:修改 TypeScript 配置
在 tsconfig.json
中配置正确的编译选项:
{
"compilerOptions": {
"module": "es2022",
"target": "es2022",
"moduleResolution": "node",
"outDir": "dist",
"esModuleInterop": true,
"strict": true
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}
关键配置说明:
"module": "es2022"
- 启用 ES 模块系统"target": "es2022"
- 目标 ECMAScript 版本"moduleResolution": "node"
- 使用 Node.js 的模块解析策略
编译命令:
npx tsc
WARNING
注意:如果直接指定文件编译(如 tsc app.ts
),TypeScript 会忽略 tsconfig.json
配置。请使用不带文件名的编译命令。
方案二:使用异步函数包装
如果无法修改 TypeScript 配置,可以将 await 包装在异步函数中:
const stripe = require('stripe')('someID');
async function createAccount() {
const account = await stripe.accounts.create({
type: 'express',
});
return account;
}
// 调用异步函数
createAccount().then(account => {
console.log('Account created:', account);
});
方案三:使用 tsx 工具
tsx 是一个无需复杂配置即可运行 TypeScript 文件的工具:
- 安装 tsx:
npm install tsx
- 在 package.json 中设置模块类型:
{
"type": "module"
}
- 运行 TypeScript 文件:
npx tsx your-file.ts
tsx 优点:
- 无需 tsconfig.json 配置
- 原生支持顶级 await
- 开发体验更友好
最佳实践建议
TIP
根据项目需求选择合适方案:
- 对于新项目,推荐使用方案一(配置 TypeScript)或方案三(使用 tsx)
- 对于现有项目,如果暂时不能修改配置,可使用方案二作为临时解决方案
常见问题
为什么需要这些配置?
顶级 await 是 ECMAScript 2022 的新特性,需要相应的模块系统和目标版本支持才能正常工作。
是否所有环境都支持顶级 await?
不是。你需要确保运行环境支持 ES2022 特性。现代 Node.js 版本(v14.8+)和现代浏览器都支持此功能。
通过正确配置 TypeScript 或使用适当的工具,你可以顺利使用顶级 await 功能,简化异步代码的编写。