如何在顶级等待下将TypeScript编译为JavaScript?

时间:2020-04-08 14:43:54

标签: javascript node.js typescript

因此,我想在NodeJS应用程序中使用TypeScript 3.8版以来的最高可用级别。 因此,下面的TypeScript代码:

import { getDoctorsPage } from "./utils/axios.provider";
const page = await getDoctorsPage("047", "1", "1");
console.log(page);

编译为以下JavaScript代码:

import { getDoctorsPage } from "./utils/axios.provider";
const page = await getDoctorsPage("047", "1", "1");
console.log(page);
//# sourceMappingURL=index.js.map

当我尝试在WebStorm中运行它时,出现以下错误:

(node:95053) ExperimentalWarning: The ESM module loader is experimental.
file:///Users/anatoly/Documents/git/maccabi-parser/dist/index.js:2
const page = await getDoctorsPage("047", "1", "1");
             ^^^^^

SyntaxError: Unexpected reserved word
    at Loader.moduleStrategy (internal/modules/esm/translators.js:81:18)
    at async link (internal/modules/esm/module_job.js:37:21)

最新的NodeJS 0.13。*是否支持它?谢谢。

我的tsconfig.json

{
  "compilerOptions": {
    "target": "es2020",
    "module": "esnext",
    "pretty": true,
    "sourceMap": true,
    "outDir": "dist",
    "importHelpers": true,
    "strict": true,
    "moduleResolution": "node",
    "esModuleInterop": true,
    "rootDir": "src",
    "noImplicitAny": false,
    "strictNullChecks": false,
    "noImplicitThis": true,
    "alwaysStrict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": false,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "baseUrl": "./",
    "allowSyntheticDefaultImports": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "resolveJsonModule": true
  },
  "include": [
    "src/**/*"
  ],
  "exclude": [
    "node_modules",
    "dist"
  ]
}

and package.json包含"type": "module"

1 个答案:

答案 0 :(得分:1)

如评论中所述,此功能不仅取决于TS的版本,还取决于WebPack的版本(如果使用WebPack的话)以及在程序执行或执行过程中存在V8标志--js-flags="--harmony-top-level-await"配置。

在启用此标志的情况下执行此代码可以按照注释中所述进行:

node -r dotenv/config --harmony-top-level-await --es-module-specifier-resolution=node dist/index.js