提问人:LoyalPotato 提问时间:7/19/2021 更新时间:1/26/2022 访问量:1365
如何在打字稿中支持顶级等待?
How to support top-level awaits in typescript?
问:
我正在使用 Ionic 的打字稿 4.3.5 版,并出现 ts(1378) 错误。
以下是 tsconfig:
{
"compilerOptions": {
"target": "es2017",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"sourceMap": true,
"noImplicitAny": true,
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "ESNext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": [
"src"
],
"exclude": [
"node_modules",
"**/*.spec.ts"
]
}
以及我收到错误的代码:
import { Storage } from '@ionic/storage';
const store = new Storage();
await store.create();
export default store;
根据错误,我需要更改的只是将目标更改为 >=es2017,将模块更改为 esnext 或系统,但我有它,它仍然向我显示错误。
不知道它是否相关,但你可以在这里看到我的文件夹结构。
提前致谢:)
答:
2赞
SamiElk
1/24/2022
#1
问题不是来自你的 tsconfig,而是来自 webpack。
顶级 await 仍然是 webpack 中的一个实验性功能。您必须包含在 webpack.config 中才能使其正常工作。experiments: { topLevelAwait: true }
https://webpack.js.org/configuration/experiments/
但是,create-react-app 会为您管理 webpackconfig 文件,您必须从 create-react-app 中弹出才能访问它们。
通常不建议从 create-react-app 中弹出,尤其是添加实验性功能时。它可能引发的问题多于解决的问题。
如果您仍想尝试,请按照以下步骤操作:
npm run eject
添加新创建的 config/webpack.config.js 的 return 语句experiments: { topLevelAwait: true }
证明这不是打字稿编译器问题。
- 创建新项目
npm init
- 仅将打字稿添加到项目中
npm install typescript --save-dev
- 使用所需的设置创建 tsc.config 文件,但目标为 es2017 或更高版本,模块为 esnext 或 system。
- 创建 1 个等待顶级的文件。
- 使用 npx tsc 进行编译。
- 一切正常。
这是我用来参考的 ts.config:
{
"compilerOptions": {
"target": "es2017",
"module": "system"
},
"include": ["topLevelAwait.ts"]
}
评论
0赞
Griffork
1/26/2022
我是那个提出这个问题的人。asker afaik 没有使用 webpack,我绝对没有使用 webpack。问题是打字稿编译器出错了。
0赞
SamiElk
1/26/2022
嗨,OP 肯定使用 webpack,因为他的 tsconfig 接近 create react app 创建的默认配置,并且 create react app 在后台使用 web pack。你使用任何框架吗?我编辑了我的答案,以证明打字稿编译器是有效的。
1赞
Griffork
1/28/2022
不,我不是。我会试一试你的更新!
0赞
Griffork
1/28/2022
即使我将“模块”更改为“ES2022”,它在我的测试项目中也确实有效。它在我的大项目中不起作用,所以那里一定有其他问题(那个项目中也没有框架)。
1赞
Griffork
3/14/2022
我想我需要更新打字稿。我怀疑更高版本的打字稿改变了 ES2022 规范的行为。
评论
async function