【问题标题】:Top-level await and Import in TypescriptTypescript 中的顶级等待和导入
【发布时间】:2022-02-13 18:24:54
【问题描述】:

我正在研究 Typescript 并遇到了问题。我想使用导入和顶级等待,但目前我一次只能使用一个。

这是我在 tsconfig.json 中的配置,它允许我使用 import

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

而这个允许我使用顶级等待:

"module":"commonjs"

我加了

"type":"module"

到我的 package.json

有什么方法可以让我同时利用这两个功能?非常感谢。

我正在使用 Nodejs 16 和 Typescript 4.5.5

【问题讨论】:

    标签: node.js typescript top-level-await


    【解决方案1】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 2021-02-13
      • 1970-01-01
      • 2021-09-21
      • 1970-01-01
      • 2022-09-28
      • 1970-01-01
      • 2021-03-26
      • 1970-01-01
      • 2021-08-03
      相关资源
      最近更新 更多