全域性庫 (Global Libraries)
全域性庫是指可以從全域性作用域訪問的庫(即無需使用任何形式的 import)。許多庫只是簡單地暴露一個或多個全域性變數供使用。例如,如果你正在使用 jQuery,可以透過簡單地引用 $ 變數來使用它。
ts$(() => {console.log("hello!");});
你通常會在全域性庫的文件中看到關於如何在 HTML 指令碼標籤中使用該庫的指導。
html<script src="http://a.great.cdn.for/someLib.js"></script>
如今,大多數流行的全域性可訪問庫實際上都是作為 UMD 庫編寫的(見下文)。UMD 庫的文件很難與全域性庫的文件區分開來。在編寫全域性宣告檔案之前,請確保該庫確實不是 UMD 庫。
從程式碼中識別全域性庫
全域性庫的程式碼通常極其簡單。一個全域性的“Hello, world”庫可能看起來像這樣:
jsfunction createGreeting(s) {return "Hello, " + s;}
或者像這樣:
jswindow.createGreeting = function (s) {return "Hello, " + s;};
當檢視全域性庫的程式碼時,通常會看到:
- 頂層的
var語句或function宣告 - 對
window.someName的一次或多次賦值 - 假設 DOM 原生物件(如
document或window)存在
你不會看到:
- 對模組載入器(如
require或define)的檢查或使用 - 形式為
var fs = require("fs");的 CommonJS/Node.js 風格的匯入 - 對
define(...)的呼叫 - 描述如何
require或匯入該庫的文件
全域性庫示例
因為將全域性庫轉換為 UMD 庫通常很容易,所以很少有流行的庫仍然以全域性風格編寫。然而,一些小型且需要 DOM(或沒有依賴項)的庫可能仍然是全域性的。
全域性庫模板
你可以在下面看到一個 DTS 示例:
ts// Type definitions for [~THE LIBRARY NAME~] [~OPTIONAL VERSION NUMBER~]// Project: [~THE PROJECT NAME~]// Definitions by: [~YOUR NAME~] <[~A URL FOR YOU~]>/*~ If this library is callable (e.g. can be invoked as myLib(3)),*~ include those call signatures here.*~ Otherwise, delete this section.*/declare function myLib(a: string): string;declare function myLib(a: number): number;/*~ If you want the name of this library to be a valid type name,*~ you can do so here.*~*~ For example, this allows us to write 'var x: myLib';*~ Be sure this actually makes sense! If it doesn't, just*~ delete this declaration and add types inside the namespace below.*/interface myLib {name: string;length: number;extras?: string[];}/*~ If your library has properties exposed on a global variable,*~ place them here.*~ You should also place types (interfaces and type alias) here.*/declare namespace myLib {//~ We can write 'myLib.timeout = 50;'let timeout: number;//~ We can access 'myLib.version', but not change itconst version: string;//~ There's some class we can create via 'let c = new myLib.Cat(42)'//~ Or reference e.g. 'function f(c: myLib.Cat) { ... }class Cat {constructor(n: number);//~ We can read 'c.age' from a 'Cat' instancereadonly age: number;//~ We can invoke 'c.purr()' from a 'Cat' instancepurr(): void;}//~ We can declare a variable as//~ 'var s: myLib.CatSettings = { weight: 5, name: "Maru" };'interface CatSettings {weight: number;name: string;tailLength?: number;}//~ We can write 'const v: myLib.VetID = 42;'//~ or 'const v: myLib.VetID = "bob";'type VetID = string | number;//~ We can invoke 'myLib.checkCat(c)' or 'myLib.checkCat(c, v);'function checkCat(c: Cat, s?: VetID);}