【问题标题】:How to export a class instance in Typescript如何在 Typescript 中导出类实例
【发布时间】:2019-06-18 11:23:37
【问题描述】:

我正在编写一个 TS 库,并且想要导出一个类的实例,我打算将它用作消费应用程序中的单例。

现在我有以下结构:

index.ts

export { Foo } from './my-class';

foo.ts

export class Foo {
  functionA() {}
}

然后我使用 webpack 和 babel 构建 UMD 格式,在另一个应用程序 (Angular) 中,我可以在我的类中导入、实例化并相应地使用它。

import { Foo } from 'foo';

private foo = new Foo();

const x = foo.functionA();

有没有办法返回我的类的实例化实例,还是我想错了?

因此,不必执行new Foo(),导入的 Foo 实际上已经是一个实例?

谢谢

更新 我应该提到,我正在导出接口等其他东西,所以我认为默认类导出不是正确的方法吗? - 见here

【问题讨论】:

    标签: angular typescript umd


    【解决方案1】:

    您可以像这样控制要返回的内容:

    // Export the named class directly
    export class Foo { }
    
    // Export the named class indirectly
    class Bar { }
    export { Bar }
    
    // Export an instance of the class directly
    export const foo = new Foo();
    
    // Export an instance of the class indirectly
    const bar = new Bar();
    export { bar };
    

    这是一个TypeScript Playground link,显示代码编译和生成的 javascript。

    用于导出(和导入以及再导出)的 TypeScript 手册官方文档:https://www.typescriptlang.org/docs/handbook/modules.html#export

    MDN 文档(由 jo_va 提供):https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export

    这是 Basarat 的指南:https://basarat.gitbooks.io/typescript/docs/project/modules.html

    【讨论】:

      【解决方案2】:

      是的,这是完全可能的,这也是在 TS 中执行此操作的标准方式。

      export default new Foo();
      

      但是,如果您不仅要导入此实例,还要导入接口,您可以像这样导出单例:

      export const foo = new Foo();
      

      您可以找到export 文档here

      【讨论】:

      • 谢谢,我已经更新了我的问题,因为我不认为默认导出是我想要的,因为我也在导出其他东西,例如接口
      【解决方案3】:

      如果你只想要单例,你应该坚持单例约定,

        export class Foo {
          private static _instance = new Foo();
          private constructor() {
      
          }
      
          static get instance() {
            return this._instance;
          }
      
        }
      
        export const foo = Foo.instance;
      

      【讨论】:

      • 所选答案也适用于单身人士。其他语言的原则不一定适合 JavaScript。
      • 我喜欢这个答案,它演示了如何在 js 中编写单例。我在导出实例(不是单例)时遇到了一些问题,然后从多个地方import 导致文件被执行多次(该文件中顶层的console.log() 运行多次)。
      • 还有一篇关于如何使用私有构造函数编写单例的visual studio杂志帖子:visualstudiomagazine.com/articles/2016/12/01/…
      • @ShaungCheng import 应在首次导入后缓存。如果将 console.log 添加到接受的答案中,您只会看到一次。如果您看到多个 console.logs 让我认为您正在执行工厂功能。
      【解决方案4】:

      可以导出成员类的实例。

      像这样导出类实例:export const playerRoutes = new Routes

      像这样导出类:export class player

      【讨论】:

        猜你喜欢
        • 2015-06-14
        • 1970-01-01
        • 2020-08-27
        • 2021-10-23
        • 1970-01-01
        • 2022-01-20
        • 1970-01-01
        • 2019-06-10
        • 2018-07-04
        相关资源
        最近更新 更多