TypeScript中的顶级await和导入

12

我正在学习 TypeScript,遇到了一个问题。我想要同时使用 import 和顶层的 await,但目前只能二选一。

以下是我的 tsconfig.json 配置,允许我使用 import

"target": "ESNext",
"module": "ESNext"

这个代码片段允许我使用顶层的 await:

"module":"commonjs"

我添加了

"type":"module"

关于我的package.json

有没有办法同时利用这两个功能呢?非常感谢。

我正在使用Nodejs 16和Typescript 4.5.5

1个回答

2

是的,你可以同时使用两者。以下是帮助您重现成功测试的信息:

Node.js(LTS)版本:

$ node --version
v16.14.0

./package.json:

{
  "name": "so-71099311",
  "version": "0.1.0",
  "private": true,
  "description": "",
  "type": "module",
  "scripts": {
    "compile": "tsc",
    "start": "npm run compile && node dist/main.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "MIT",
  "dependencies": {
    "@types/node": "^17.0.17",
    "typescript": "^4.5.5"
  }
}


./tsconfig.json:

{
  "compilerOptions": {
    "esModuleInterop": true,
    "exactOptionalPropertyTypes": true,
    "isolatedModules": true,
    "lib": [
      "esnext"
    ],
    "module": "esnext",
    "moduleResolution": "node",
    "noUncheckedIndexedAccess": true,
    "outDir": "dist",
    "strict": true,
    "target": "esnext",
    "useUnknownInCatchVariables": true
  },
  "include": [
    "./src/**/*"
  ]
}


./src/module.ts:

export function greet (name = 'world'): void {
  console.log(`Hello ${name}`);
}


./src/main.ts:

import {greet} from './module.js';

const name = await Promise.resolve('Nguyen');
greet(name);


在你的控制台中:

$ cd /path/to/the/directory/where/you/created/these/files
$ npm install
$ npm run start

> so-71099311@0.1.0 start
> npm run compile && node dist/main.js


> so-71099311@0.1.0 compile
> tsc

Hello Nguyen

3
那不行。你导入了'./module.js',但应该是'./module.ts'。而你不能将导入改为以.ts结尾,因为不允许这样做。你也不能完全删除.js,因为有"type": "module"。这是一个进退两难的局面。 - leonheess
@leonheess 如果你将文件复制到设备上并运行代码,你会发现它确实可以工作。TypeScript会解析以.js结尾的特定符号,这些符号是本地模块,将其相应地转换为.ts对应项。 - jsejcksn
不行?所有的.js文件都在dist目录下。无法找到模块“./module.js”或其对应的类型声明。 - leonheess
1
@leonheess 你可能希望参考模块解析文档来刷新/学习TS解析规范的方式。如果你按照步骤做的话,那么在使用Node.js >= 16.14时就不应该看到那个错误信息。以下命令的输出是什么?node --version && cat -b ./package.json ./tsconfig.json ./src/module.ts ./src/main.ts && tsc --traceResolution - jsejcksn

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接