网站搜索

reactjs - 如何在 TypeScript 中支持顶层 await?


我正在使用 4.3.5 版本的 TypeScript 与 Ionic,并且遇到了 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 或 system,但我已经这样设置了,它仍然显示错误。

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

提前谢谢你 :)

答案#1

问题不在于你的 tsconfig,而在于 webpack。

顶层 await 在 webpack 中仍然是实验性功能。你必须在你的 webpack.config 中加入 experiments: { topLevelAwait: true } 才能使其工作。

https://webpack.js.org/configuration/experiments/

然而,create-react-app 会为你管理 webpack 配置文件,如果你想访问它们,就必须从 create-react-app 中弹出。

通常不建议从 create-react-app 弹出,特别是为了添加实验性功能。这可能会引发比解决的问题更多的问题。

如果你仍然想尝试,以下是需要遵循的步骤:

npm run eject

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

以证明这不是 TypeScript 编译器的问题。

  1. 创建一个新项目 npm init
  2. 只向你的项目添加 TypeScript npm install typescript --save-dev
  3. 使用你想要的设置创建你的 tsc.config 文件,但 target 为 es2017 或更高版本,module 为 esnext 或 system。
  4. 创建一个含有顶层 await 的文件。
  5. 使用 npx tsc 编译。
  6. 一切正常。

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

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