如何建立高質量的TypeScript宣告檔案(二)
繼續上篇文章[ofollow,noindex">如何建立高質量的TypeScript宣告檔案(一) ]
模組化庫
有些庫只能在模組載入器環境中工作。 例如,因為express僅適用於Node.js,必須使用CommonJS require函式載入。
ECMAScript 2015(也稱為ES2015,ECMAScript 6和ES6),CommonJS和RequireJS具有類似的匯入模組的概念。 例如,在JavaScript CommonJS(Node.js)中,您可以編寫
var fs = require("fs");
在TypeScript或ES6中,import關鍵字用於相同的目的:
import fs = require("fs");
您通常會看到模組化庫在其文件中包含以下行之一:
var someLib = require('someLib');
或
define(..., ['someLib'], function(someLib) { });
與全域性模組一樣,您可能會在UMD模組的文件中看到這些示例,因此請務必檢視程式碼或文件。
從程式碼中識別模組庫
模組化庫通常至少具有以下某些功能:
- 無條件呼叫require或define
- import * as a from 'b'的宣告,或export c;
- 對exports或module.exports的賦值
他們很少會:
- 分配window或global的屬性
模組化庫的示例
許多流行的Node.js庫都在模組系列中,例如express,gulp和request。
UMD
UMD模組可以用作模組(通過匯入),也可以用作全域性模組(在沒有模組載入器的環境中執行)。 許多流行的庫,如Moment.js,都是以這種方式編寫的。 例如,在Node.js中或使用RequireJS,您可以編寫:
import moment = require("moment"); console.log(moment.format());
而在vanilla瀏覽器環境中,你會寫:
console.log(moment.format());
識別UMD庫
UMD模組檢查是否存在模組載入器環境。 這是一個易於檢視的模式,看起來像這樣:
(function (root, factory) { if (typeof define === "function" && define.amd) { define(["libName"], factory); } else if (typeof module === "object" && module.exports) { module.exports = factory(require("libName")); } else { root.returnExports = factory(root.libName); } }(this, function (b) {
如果您在庫的程式碼中看到typeof define,typeof window或typeof module的測試,特別是在檔案的頂部,它幾乎總是一個UMD庫。
UMD庫的文件通常還會演示一個"Using in Node.js"示例,其中顯示了require,以及一個"Using in the browser"示例,該示例顯示了使用<script>
標記載入指令碼。
UMD庫的示例
大多數流行的庫現在都可以作為UMD包使用。 示例包括jQuery,Moment.js,lodash等等。
模板
模組有三個模板,module.d.ts,module-class.d.ts和module-function.d.ts。
如果您的模組可以像函式一樣被呼叫,請使用module-function.d.ts:
var x = require("foo"); // Note: calling 'x' as a function var y = x(42);
請務必閱讀腳註"ES6對模組呼叫簽名的影響 "
如果您的模組可以使用new構建,請使用module-class.d.ts:
var x = require("bar"); // Note: using 'new' operator on the imported variable var y = new x("hello");
同樣的腳註適用於這些模組。
如果您的模組不可呼叫或可構造,請使用module.d.ts檔案。
未完待續...