網站搜尋

angular - 如何在 Typescript 中導出類實例


我正在撰寫一個 TypeScript 函式庫,並希望匯出一個類別的實例,我打算讓它在使用這個函式庫的應用程式中被作為單例使用。

現在我有以下結構:

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 實際上已經是一個實例了嗎?

謝謝

更新 我應該提到,我正在匯出其他東西,例如介面,所以我認為預設的類別匯出可能不是正確的做法,對吧?- 看這裡

答案#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 連結,顯示程式碼可以編譯以及生成的 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 文件