TypeScript基礎入門之模組(四)
使用其他JavaScript庫
要描述不是用TypeScript編寫的庫的形狀,我們需要宣告庫公開的API。
我們稱之為未定義實現"環境"的宣告。
通常,這些是在.d.ts檔案中定義的。
如果您熟悉C/C++,可以將它們視為.h檔案。
我們來看幾個例子。
外部模組
在Node.js中,大多數任務是通過載入一個或多個模組來完成的。
我們可以使用頂級匯出宣告在自己的.d.ts檔案中定義每個模組,但將它們編寫為一個較大的.d.ts檔案會更方便。
為此,我們使用類似於環境名稱空間的構造,但我們使用模組關鍵字和模組的引用名稱,以便稍後匯入。
例如:
node.d.ts (simplified excerpt)
declare module "url" { export interface Url { protocol?: string; hostname?: string; pathname?: string; } export function parse(urlStr: string, parseQueryString?, slashesDenoteHost?): Url; } declare module "path" { export function normalize(p: string): string; export function join(...paths: any[]): string; export var sep: string; }
現在我們可以/// <reference> node.d.ts 並且使用import url = require("url"); 或import * as URL from "url" 載入模組。
/// <reference path="node.d.ts" /> import * as URL from "url"; let testUrl = URL.parse("https://www.gowhich.com");
外部模組簡寫
如果您不想在使用新模組之前花時間寫出宣告,則可以使用速記宣告快速入門。
declarations.d.ts
declare module "hot-new-module";
從速記模組匯入的所有內容都將具有any型別
import x, {y} from "hot-new-module"; x(y);
萬用字元模組宣告
某些模組載入器(如SystemJS和AMD)允許匯入非JavaScript內容。
這些通常使用字首或字尾來指示特殊的載入語義。
萬用字元模組宣告可用於涵蓋這些情況。
declare module "*!text" { const content: string; export default content; } // Some do it the other way around. declare module "json!*" { const value: any; export default value; }
現在您可以匯入與"*text"或"json*"匹配的內容。
import fileContent from "./xyz.txt!text"; import data from "json!http://example.com/data.json"; console.log(data, fileContent);
UMD模組
有些庫設計用於許多模組載入器,或者沒有模組載入(全域性變數)。
這些被稱為UMD模組。
可以通過匯入或全域性變數訪問這些庫。
例如:
math-lib.d.ts
export function isPrime(x: number): boolean; export as namespace mathLib;
然後,該庫可用作模組中的匯入:
import { isPrime } from "math-lib"; isPrime(2); mathLib.isPrime(2); // ERROR: can't use the global definition from inside a module
它也可以用作全域性變數,但僅限於指令碼內部。(指令碼是沒有匯入或匯出的檔案。)
mathLib.isPrime(2);