UMD是AMD和CommonJS的结合
AMD是以浏览器为出发点的异步加载模块
CommonJS是以服务器为出发点的同步加载模块
所以人们想出了另一个更通用的模式UDM,
来解决跨平台的问题。
(function (root, factory) {
if (typeof exports === 'object') {
// Commonjs
module.exports = factory();
} else if (typeof define === 'function' && define.amd) {
// AMD
define(factory);
} else {
// 没有使用模块加载器的方式
window.eventUtil = factory();
}
})(this, function() {
// module
return {
addEvent: function(el, type, handle) {
//...
},
removeEvent: function(el, type, handle) {
},
};
});
根据jquery 源码提取。
(支持amd、cmd、commonjs规范的模块加载)
;(function( global, factory ){
"use strict";
if ( typeof module === "object" && typeof module.exports === "object" ) {
// For CommonJS and CommonJS-like environments where a proper window
// is present, execute the factory and get jQuery.
// For environments that do not have a window
with a document
// (such as Node.js), expose a factory as module.exports.
// This accentuates the need for the creation of a real window
.
// See ticket #14549 for more info.
module.exports = global.document ?
factory( global, true ) :
function( w ) {
if ( !w.document ) {
throw new Error( "jQuery requires a window with a document" );
}
return factory( w );
};
} else if (define && define.cmd) {
define( function () {
return factory(global);
} );
} else {
factory( global );
}
})( typeof window !== "undefined" ? window : this, function( window, noGlobal ) {
// 核心逻辑代码...
// 使代码支持 amd 模块加载
if ( typeof define === "function" && define.amd ) {
define( "jquery", [], function() {
return jQuery;
} );
}
return {
add: function(a, b) { return a + b }
}
})