如何在Typescript中导出一个类实例

27
我正在编写一个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();

有没有一种方法可以返回我的类的实例化实例,或者我想错了?

所以,导入Foo时,不需要执行new Foo(),而是已经存在一个实例化的Foo?

谢谢

更新 我应该提到,我正在导出其他东西,例如接口,因此我认为默认类导出不是正确的方法,对吗?-请参见这里

4个回答

49

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

// 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链接,展示了代码编译和生成的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


17

是的,这完全可以做到,并且在TS中也是标准的方法。

export default new Foo();
如果您想不仅导入该实例还要导入接口,那么您应该像这样导出单例:
export const foo = new Foo();

你可以在这里找到export文档。


谢谢,我已经更新了我的问题,因为我认为默认导出并不是我想要的,因为我还要导出其他东西,比如接口。 - mindparse

7
如果您只想使用单例模式,那么应该坚持单例约定。
  export class Foo {
    private static _instance = new Foo();
    private constructor() {

    }

    static get instance() {
      return this._instance;
    }

  }

  export const foo = Foo.instance;

2
所选答案对于单例模式同样适用。其他语言的原则不一定适用于JavaScript。 - RA.
我喜欢这个回答,它演示了如何在JS中编写单例。当我导出实例(而不是单例)并从多个位置import时,我遇到了一些问题,导致文件被多次执行(该文件顶层的console.log()运行多次)。 - Shawn
还有一篇《Visual Studio Magazine》的文章详细介绍了如何使用私有构造函数编写单例模式:https://visualstudiomagazine.com/articles/2016/12/01/defining-classes.aspx - Shawn
@ShaungCheng 在第一次导入后,应该缓存 import。如果在接受的答案中添加了 console.log,您只会看到一次。如果您看到多个 console.log,那么我认为您正在执行一个工厂函数。 - Alex

3

可以导出类Members的实例。

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

像这样导出类:export class player


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