每晚等待 Node 17 和 TypeScript 的顶级

Top-level Await Node 17 & TypeScript nightly

我有一个简单的脚本试图用 Node 和 TypeScript 测试顶级 await。

import { readFile } from "fs/promises";

async function getNum(filename: string) {
  return parseInt(await readFile(filename, "utf8"), 10);
}

try {
  const numberPromises = [1, 2, 3].map((i) => getNum(`${i}.txt`));
  const numbers = await Promise.all(numberPromises);
  console.log(numbers[0], numbers[1], numbers[2]);
} catch (err) {
  console.error("Something went wrong");
  console.error(err);
}

当我尝试使用 TypeScript 编译时出现此错误:

error TS1378: Top-level 'await' expressions are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', or 'nodenext', and the 'target' option is set to 'es2017' or higher.

第9行顶层await触发:

const numbers = await Promise.all(numberPromises);

我很困惑,因为我已经完成了错误消息中提到的两件事,并且我已尝试尽可能地配对我的 tsconfig.json

{
  "compilerOptions": {
    "module": "es2022",
    "target": "es2017",
    "outDir": "dist",
    "strict": true,
    "moduleResolution": "Node"
  }
}

我的 package.json 文件中也有 type: module

{
  "name": "ts-test",
  "version": "1.0.0",
  "type": "module",
  "devDependencies": {
    "@types/node": "^17.0.5",
    "typescript": "^4.6.0-dev.20211226"
  },
  "scripts": {
    "dev": "node dist/script.js",
    "compile": "tsc script.ts"
  },
  "author": "Todd Matthews",
  "license": "ISC",
  "volta": {
    "node": "17.3.0"
  }
}

任何关于如何使用 Node 和 TypeScript 测试顶级 await 的帮助都将不胜感激!

我会为你提供一个不依赖任何文件系统的更简单的复现案例API,我会包括所有的repo文件和命令:

文件

./package.json:

{
  "name": "so-70491077",
  "version": "1.0.0",
  "description": "",
  "type": "module",
  "main": "dist/main.ts",
  "scripts": {
    "test": "tsc && node dist/main.js"
  },
  "author": "",
  "license": "MIT",
  "devDependencies": {
    "typescript": "^4.5.4"
  }
}

./tsconfig.json:

{
  "compilerOptions": {
    "module": "es2022",
    "target": "es2017",
    "outDir": "dist",
    "strict": true,
    "moduleResolution": "Node"
  },
  "files": ["main.ts"]
}

./main.ts:

export async function getRandom (): Promise<number> {
  return Math.random();
}

const n = await getRandom();
console.log(n);

命令

cd /path/to/the/dir/where/you/stored/the/files/above
npm i
npm test

输出

> so-70491077@1.0.0 test
> tsc && node dist/main.js

0.9303778211654203 # a similar floating point number

您的代码和 tsconfig.json 没问题。但是 tsc 不使用 tsconfig.json 文件。来自文档 What is a tsconfig.json:

When input files are specified on the command line, tsconfig.json files are ignored.

因此,不要为 compile npm 脚本指定输入文件。

"scripts": {
   "compile": "tsc"
}