TypeScript基礎入門之模組(三)
可選模組載入和其他高階載入方案
在某些情況下,您可能只想在某些條件下載入模組。在TypeScript中,我們可以使用下面顯示的模式來實現此模式和其他高階載入方案,以直接呼叫模組載入器而不會丟失型別安全性。
編譯器檢測是否生成的JavaScript中使用了每個模組。如果模組識別符號僅用作型別註釋的一部分而從不用作表示式,則不會為該模組生成require呼叫。這種未使用的引用的省略是一種良好的效能優化,並且還允許可選地載入這些模組。
該模式的核心思想是import id = require("...") 語句使我們能夠訪問模組公開的型別。
模組載入器是動態呼叫的(通過require),如下面的if塊所示。
這利用了參考省略優化,因此模組僅在需要時載入。
為了使這個模式起作用,重要的是通過匯入定義的符號僅用於型別位置(即從不在將被生成到JavaScript中的位置)。
為了保持型別安全,我們可以使用typeof關鍵字。
typeof關鍵字在型別位置使用時會生成值的型別,在本例中為模組的型別。
**示例:Node.js裡的動態模組載入**
declare function require(moduleName: string): any; import { ZipCodeValidator as Zip } from "./ZipCodeValidator"; if (needZipValidation) { let ZipCodeValidator: typeof Zip = require("./ZipCodeValidator"); let validator = new ZipCodeValidator(); if (validator.isAcceptable("...")) { /* ... */ } }
**示例:require.js裡的動態模組載入**
declare function require(moduleNames: string[], onLoad: (...args: any[]) => void): void; import * as Zip from "./ZipCodeValidator"; if (needZipValidation) { require(["./ZipCodeValidator"], (ZipCodeValidator: typeof Zip) => { let validator = new ZipCodeValidator.ZipCodeValidator(); if (validator.isAcceptable("...")) { /* ... */ } }); }
**示例:System.js裡的動態模組載入**
declare const System: any; import { ZipCodeValidator as Zip } from "./ZipCodeValidator"; if (needZipValidation) { System.import("./ZipCodeValidator").then((ZipCodeValidator: typeof Zip) => { var x = new ZipCodeValidator(); if (x.isAcceptable("...")) { /* ... */ } }); }