【问题标题】:How to support top-level awaits in typescript?如何在打字稿中支持顶级等待?
【发布时间】:2021-09-27 07:05:09
【问题描述】:

我正在使用带有 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 或系统,但我有,它仍然显示错误。

不知道是否相关,但你可以看到我的文件夹结构here

提前致谢:)

【问题讨论】:

  • 你确定一个 target >= es2017 就足够了吗?顶级等待是第 4 阶段的提案,因此甚至不是 es2020 的一部分。
  • 我只是根据错误进行,但我只是尝试将目标设置为 ES2021 并且仍然有相同的错误
  • 作为一种解决方法,您可以将代码包装在自动执行的 async function 中。
  • @Thomas 是的,我做到了,只是想知道我是做错了什么还是错过了什么
  • @LoyalPotato - stackoverflow.com/a/69789625/4376643 - 这是关于让它与 typescript 和 ts-node 一起工作。 stefanjudis.com/today-i-learned/… - 是关于让它与 nodejs 一起使用。秘诀是让 TS 设置生成 ES 代码,而不是 CommonJS。所以它是两种参考的混合体。

标签: reactjs typescript ionic-framework async-await ecmascript-2017


【解决方案1】:

问题不是来自您的 tsconfig,而是来自 webpack。

顶级等待仍然是 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 }

为了证明这不是打字稿编译器问题。

  1. 新建项目npm init
  2. 只将打字稿添加到您的项目npm install typescript --save-dev
  3. 使用您想要的设置创建您的 tsc.config 文件,但使用目标 es2017 或更高版本以及模块 esnext 或系统。
  4. 创建 1 个具有顶级等待的文件。
  5. 使用 npx tsc 编译。
  6. 一切正常。

这是我用来参考的 ts.config:

{
    "compilerOptions": {
        "target": "es2017",
        "module": "system"
    },
    "include": ["topLevelAwait.ts"]
}

【讨论】:

  • 我是提出问题的人。提问者 afaik 没有使用 webpack,我绝对没有使用 webpack。问题是打字稿编译器出错了。
  • 嗨,OP 肯定在使用 webpack,因为他的 tsconfig 接近 create react app 创建的默认配置,并且 create react app 在后台使用 webpack。你在使用任何框架吗?我编辑了我的答案以证明 typescript 编译器可以工作。
  • 不,我不是。我会试试你的更新!
  • 即使我将“模块”更改为“ES2022”,它也确实在我的测试项目中工作。它在我的大项目中不起作用,所以那里肯定有其他问题(也没有框架)。
猜你喜欢
  • 2020-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-16
  • 2020-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多