programing

유형 스크립트에서 클래스 인스턴스를 내보내는 방법

linuxpc 2023. 6. 10. 08:31
반응형

유형 스크립트에서 클래스 인스턴스를 내보내는 방법

TS 라이브러리를 작성하고 있으며 클래스 인스턴스를 내보내고 싶습니다. 사용 애플리케이션에서 싱글톤으로 사용하려고 합니다.

현재 저는 다음과 같은 구조를 가지고 있습니다.

index.

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

풋스

export class Foo {
  functionA() {}
}

그런 다음 웹팩과 바벨을 사용하여 UMD 형식으로 빌드하고 있으며, 다른 애플리케이션(Angular)에서는 클래스에서 가져와서 인스턴스화하고 그에 따라 사용할 수 있습니다.

import { Foo } from 'foo';

private foo = new Foo();

const x = foo.functionA();

제 수업의 인스턴스화된 인스턴스를 반환하는 방법이 있나요? 아니면 제가 잘못된 방법으로 생각하고 있나요?

그래서 그렇게 하는 대신에new Foo()수입된 Foo가 실제로 이미 사례가 되었을까요?

감사해요.

업데이트를 언급했어야 했습니다. 인터페이스와 같은 다른 항목을 내보내고 있기 때문에 기본 클래스 내보내기가 올바른 방법이라고 생각하지 않습니다. - 여기를 참조하십시오.

반환되는 항목을 다음과 같이 제어할 수 있습니다.

// 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 링크가 있습니다.

내보내기(및 가져오기 및 재내보내기)에 대한 TypeScript Handbook 공식 문서: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 .

네, 이것은 완전히 가능하며, TS에서도 표준 방식입니다.

export default new Foo();

그러나 이 인스턴스뿐만 아니라 인터페이스도 가져오려면 다음과 같이 싱글톤을 내보냅니다.

export const foo = new Foo();

다음을 찾을 수 있습니다.export여기에 의사가 되다

만약 당신이 싱글톤만을 원한다면, 당신은 싱글톤 관습을 고수해야 합니다.

  export class Foo {
    private static _instance = new Foo();
    private constructor() {

    }

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

  }

  export const foo = Foo.instance;

클래스 구성원의 인스턴스를 내보낼 수 있습니다.

클래스 인스턴스를 다음과 같이 내보냅니다.export const playerRoutes = new Routes

클래스를 다음과 같이 내보냅니다.export class player

언급URL : https://stackoverflow.com/questions/54351492/how-to-export-a-class-instance-in-typescript

반응형