reactjs - 如何在 typescript 中支持顶级等待?

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

我在 Ionic 中使用 typescript 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 .

提前致谢:)

最佳答案

问题不是来自您的 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 pop

在新创建的 config/webpack.config.js 的 return 语句中添加 experiments: { topLevelAwait: true }

证明这不是 typescript 编译器问题。

  1. 创建一个新项目npm init
  2. 仅将 typescript 添加到您的项目中 npm install typescript --save-dev
  3. 使用所需的设置创建 tsc.config 文件,但目标为 es2017 或更高版本,模块为 esnext 或 system。
  4. 创建 1 个包含顶级等待的文件。
  5. 使用 npx tsc 进行编译。
  6. 一切正常。

这是我用作引用的 ts.config:

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

关于reactjs - 如何在 typescript 中支持顶级等待?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68443510/

相关文章:

cordova - 问 : Ionic3 saving base64Image as image using cordova-base64-to-image plugin

javascript - 输入表单在reactjs中发送空白值

python - django+nginx部署无法正确加载静态文件

typescript - 在 TypeScript 中创建类似静态的类或模块层次结构?

javascript - 如何创建if语句来处理html中的空字符串

node.js - 类型错误 : Cannot read property 'substr' of undefined - source-node. js

reactjs - 尝试在 vs code 中将 emmet 与 React 应用程序一起使用

reactjs - 在开发模式下使用 ReactJS 在 Azure 上发布 asp.net Core 2.0 WebApp

javascript - Angular 2路由器事件监听器

typescript - 如何使用 typescript 编写 marionettejs 模块?