全域性:修改模組

全域性修改模組 (Global-modifying Modules)

全域性修改模組在被匯入時會更改全域性作用域中現有的值。例如,可能存在一個庫,在被匯入時會向 String.prototype 新增新成員。這種模式由於可能導致執行時衝突,因此具有一定的危險性,但我們仍然可以為其編寫宣告檔案。

識別全域性修改模組

通常很容易從文件中識別出全域性修改模組。一般來說,它們類似於全域性外掛,但需要透過 require 呼叫來啟用它們的效果。

你可能會看到如下文件

js
// 'require' call that doesn't use its return value
var unused = require("magic-string-time");
/* or */
require("magic-string-time");
var x = "hello, world";
// Creates new methods on built-in types
console.log(x.startsWithHello());
var y = [1, 2, 3];
// Creates new methods on built-in types
console.log(y.reverseAndSort());

這裡是一個示例

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 global-modifying module 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'
*/
/*~ Note: If your global-modifying module is callable or constructable, you'll
*~ need to combine the patterns here with those in the module-class or module-function
*~ template files
*/
declare global {
/*~ Here, declare things that go in the global namespace, or augment
*~ existing declarations in the global namespace
*/
interface String {
fancyFormat(opts: StringFormatOptions): string;
}
}
/*~ If your module exports types or values, write them as usual */
export interface StringFormatOptions {
fancinessLevel: number;
}
/*~ For example, declaring a method on the module (in addition to its global side effects) */
export function doSomething(): void;
/*~ If your module exports nothing, you'll need this line. Otherwise, delete it */
export {};

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

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

最後更新:2026 年 3 月 27 日