【问题标题】:Top-level Await Node 17 & TypeScript nightly顶级 Await Node 17 和 TypeScript 每晚
【发布时间】:2022-01-26 03:48:21
【问题描述】:

我有一个简单的脚本尝试使用 Node 和 TypeScript 测试顶级等待。

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 编译时出现此错误:

错误 TS1378:仅当 'module' 选项设置为 'es2022'、'esnext'、'system' 或 'nodenext' 并且设置了 'target' 选项时,才允许使用顶级 'await' 表达式到 'es2017' 或更高版本。

由line9上的顶级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 的帮助将不胜感激!

【问题讨论】:

  • 我认为你可以尝试在 tsconfig.json 中设置 module: 'commonjs'

标签: node.js typescript async-await


【解决方案1】:

我将为您提供一个更简单的复制案例,它不依赖任何文件系统 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

【讨论】:

    【解决方案2】:

    您的代码和tsconfig.json 都很好。但 tsc 不使用 tsconfig.json 文件。来自文档What is a tsconfig.json

    在命令行中指定输入文件时,tsconfig.json 文件将被忽略。

    所以,不要为compile npm 脚本指定输入文件。

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

    【讨论】:

    • 注意输入文件还是可以在配置文件本身中指定的
    猜你喜欢
    • 2021-02-13
    • 1970-01-01
    • 1970-01-01
    • 2016-08-22
    • 1970-01-01
    • 2018-06-07
    • 1970-01-01
    • 2011-11-22
    • 1970-01-01
    相关资源
    最近更新 更多