如何在typescript/node/stencil js/jsx中启用顶级await

zsohkypk  于 2023-04-05  发布在  Node.js
关注(0)|答案(1)|浏览(118)

如何在typescript中启用顶级await?tsconfig设置是什么?我已经尝试了常见的设置,例如模块中的esnext和目标es2017或更高版本。顶级await可以在ts文件中吗?还是必须在另一个文件中,例如mjs或js?
我使用node和stencil js沿着typescript。
我继续得到这个错误:模块格式cjs不支持顶级的await。请使用“es”或“system”输出格式。
在tsconfig中,我尝试了常见的设置,例如模块中的esnext和目标es2017或更高版本。
我可以导出一个没有promise的对象。
示例

export class Hello{
    static async SayHello() {
      return new Promise(resolve => { resolve("Hello World")})
        }
    }

    export const hello = await Hello.SayHello(); 

    //in another ts file 
    import {hello} from 'Hello.ts' 
    console.log(hello);
anauzrmj

anauzrmj1#

嗨!😊
我创建了以下文件:
package.json

{
  "name": "hello",
  "version": "1.0.0",
  "description": "",
  "type": "module",
  "main": "index.js",
  "scripts": {
    "build": "tsc"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "typescript": "^5.0.3"
  }
}

tsconfig.json

{
  "compilerOptions": {
    "module": "esnext",
    "moduleResolution": "node",
    "outDir": "dist",
    "rootDir": "src",
    "target": "es2017"
  },
  "exclude": ["dist", "node_modules"]
}

src/Hello.ts

export class Hello {
  static async SayHello() {
    return new Promise((resolve) => {
      resolve("Hello World");
    });
  }
}

export const hello = await Hello.SayHello();

源代码/索引.ts

import { hello } from "./Hello";
console.log("test");
console.log(hello);

这似乎是做的把戏。😊
也就是说,你确定要将SayHello导出为一个函数,而不是整个类Hello吗?

相关问题