모듈: 플러그인
모듈: 플러그인 (Module: Plugin)
다른 라이브러리를 확장하는 모듈의 타입 정의를 만들 때 쓰는 템플릿이에요. 플러그인은 기존 모듈에 새 기능을 덧붙이기 때문에, 새 모듈 타입을 만드는 게 아니라 기존 모듈의 선언을 넓히는(expand) 작업이 됩니다. 이 과정의 바탕에는 선언 병합(declaration merging)이 깔려 있어요.
출처: TypeScript 핸드북
언제 쓰는 템플릿인가요?
다른 라이브러리를 확장하는 자바스크립트 코드와 함께 작업하고 싶을 때를 떠올려 보세요.
import { greeter } from "super-greeter";
// Normal Greeter API
greeter(2);
greeter("Hello world");
// Now we extend the object with a new function at runtime
import "hyper-super-greeter";
greeter.hyperGreet();
여기서 "super-greeter"의 정의는 다음과 같다고 가정할게요.
/*~ This example shows how to have multiple overloads for your function */
export interface GreeterFunction {
(name: string): void
(time: number): void
}
/*~ This example shows how to export a function specified by an interface */
export const greeter: GreeterFunction;
플러그인(hyper-super-greeter)은 기존 greeter 객체의 선언을 이렇게 확장할 수 있어요.
// Type definitions for [~THE LIBRARY NAME~] [~OPTIONAL VERSION NUMBER~]
// Project: [~THE PROJECT NAME~]
// Definitions by: [~YOUR NAME~] <[~A URL FOR YOU~]>
/*~ This is the module plugin template file. You should rename it to index.d.ts
*~ and place it in a folder with the same name as the module.
*~ For example, if you were writing a file for "super-greeter", this
*~ file should be 'super-greeter/index.d.ts'
*/
/*~ On this line, import the module which this module adds to */
import { greeter } from "super-greeter";
/*~ Here, declare the same module as the one you imported above
*~ then we expand the existing declaration of the greeter function
*/
export module "super-greeter" {
export interface GreeterFunction {
/** Greets even better! */
hyperGreet(): void;
}
}
핵심은 export module "super-greeter"로 확장 대상 모듈을 같은 이름으로 다시 선언하면서, 그 안에 새 멤버(hyperGreet)를 추가하는 방식이에요. 컴파일러는 이 두 선언을 하나로 병합해서, 기존 greeter 함수가 hyperGreet도 호출할 수 있게 해 줍니다. 여기서 쓰이는 기법이 바로 선언 병합 (declaration merging)이에요.
ES6가 모듈 플러그인에 미치는 영향
일부 플러그인은 기존 모듈의 최상위 내보내기를 추가하거나 수정합니다. CommonJS나 다른 로더에서는 합법적이지만, ES6 모듈은 **불변(immutable)**으로 간주되기 때문에 이런 패턴이 동작하지 않아요. TypeScript는 로더에 종속적이지 않아 이 정책을 컴파일 시점에 강제하지 않지만, ES6 모듈 로더로 전환하려는 개발자는 이 점을 꼭 알아두어야 합니다.
더 알아보기 (Learn more)
- 선언 병합 (Declaration Merging) — 모듈 플러그인의 바탕이 되는 기법
- Modules 참고 문서