模組:外掛

例如,當你想要使用一段擴充套件了其他庫的 JavaScript 程式碼時。

ts
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” 的定義

ts
/*~ 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;

我們可以按如下方式擴充套件現有模組

ts
// 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;
}
}

這裡使用了 宣告合併

ES6 對模組外掛的影響

有些外掛會新增或修改現有模組的頂級匯出。雖然這在 CommonJS 和其他載入器中是合法的,但 ES6 模組被認為是不可變的,因此這種模式將不再適用。由於 TypeScript 與載入器無關,所以在此策略上沒有編譯時的強制約束,但打算過渡到 ES6 模組載入器的開發者應該意識到這一點。

TypeScript 文件是一個開源專案。請透過 提交 Pull Request 來幫助我們改進這些頁面 ❤

此頁面的貢獻者
MHMohamed Hegazy (53)
OTOrta Therox (14)
BB2D1 (1)
1+

最後更新:2026 年 3 月 27 日