Universal Module Definition UMD
suggest changeThe UMD (Universal Module Definition) pattern is used when our module needs to be imported by a number of different module loaders (e.g. AMD, CommonJS).
The pattern itself consists of two parts:
- An IIFE (Immediately-Invoked Function Expression) that checks for the module loader that is being implemented by the user. This will take two arguments;
root(athisreference to the global scope) andfactory(the function where we declare our module). - An anonymous function that creates our module. This is passed as the second argument to the IIFE portion of the pattern. This function is passed any number of arguments to specify the dependencies of the module.
The example checks for AMD, then CommonJS. If neither loader is in use, it falls back to a global. It expects a classic non-strict script: at the top level of a module, this is undefined, so root.b would throw.
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['exports', 'b'], factory);
} else if (typeof exports === 'object' && typeof exports.nodeName !== 'string') {
// CommonJS
factory(exports, require('b'));
} else {
// Browser globals
factory((root.commonJsStrict = {}), root.b);
}
}(this, function (exports, b) {
//use b in some fashion.
// attach properties to the exports object to define
// the exported module properties.
exports.action = function () {};
}));
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents