UMD (Universal Module Definition), 希望提供一个前后端跨平台的解决方案(支持AMD与CommonJS模块方式),。
一般是挂载在window或者global上的一个对象可以直接获取
实现原理
UMD的实现很简单:
- 先判断是否支持Node.js模块格式(exports是否存在),存在则使用Node.js模块格式。
- 再判断是否支持AMD(define是否存在),存在则使用AMD方式加载模块。
- 前两个都不存在,则将模块公开到全局(window或global)。
各种具体的实现方式,可以查看UMD的github。我这里举例一个jQuery使用的,按照如上方式实现的代码:
// if the module has no dependencies, the above pattern can be simplified to(function (root, factory) {if (typeof define === 'function' && define.amd) {// AMD. Register as an anonymous module.define([], factory);} else if (typeof exports === 'object') {// Node. Does not work with strict CommonJS, but// only CommonJS-like environments that support module.exports,// like Node.module.exports = factory();} else {// Browser globals (root is window)root.returnExports = factory();}}(this, function () {// Just return a value to define the module export.// This example returns an object, but the module// can return a function as the exported value.return {};}));
