本篇为大家介绍如何肉眼识别库的类型,为更好的理解后面即将要介绍的声明文件做好充足准备。
全局库是指能在全局命名空间下访问,不需要 import、require,例如:jQuery.
$(() => { console.log('hello!') } )全局库源码中,通常会看到以下 3 点:
- 顶级的
var语句或者function函数声明; - 一个或者多个赋值语句到
window; - 假设 DOM 原始值
document或者window存在.
全局库你不会看到:
- 检查是否使用或者如何使用模块加载器,比如
require或define - CommonJS / Node.js 风格的导入,如
var fs = require("fs") define(...)调用- 使用文档说明如何去
require、import导入该库
一些库只能工作在模块加载器的环境下。 比如,像 express 只能在 Node.js 里工作所以必须使用 CommonJS 的 require 函数加载。
如:
// CommonJS (Node.js)
var fs = require("fs")
// ES6
import fs = require("fs")
// or
define(..., ['someLib'], function(someLib) {
})特征:
- 使用
require或define - 使用
import或export - 使用
exports或module.exports
UMD模块既可以作为模块引入又可以作为全局使用
UMD模块会检查是否存在模块加载器环境,如果在源码里看到 typeof define、typeof window 或 typeof module 关键字,尤其是在文件顶端,那么它几乎就是一个 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) {