UMD, or Universal Module Definition, is a module definition format that aims to be compatible with both CommonJS and AMD. It also allows you to export the module as a global variable that you can include in your application through a simple <script> tag.
It does this by wrapping the modules in a boilerplate that checks the environment to detect how the module is used, and produces the correct exported object.
For example, the preceding greeter example would look like this with UMD:
// greeter.js
(function (root, factory) {
// Requirements are defined here
}(this, function () {
function helloWorld(name) {
process.stdout.write(`hello ${name}!\n`
};
// Whatever you return is exposed
return {
helloWorld: helloWorld
}
}));
// main.js
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD
define(['./greeter.js'], factory);
} else if (typeof exports === 'object') {
// Node, CommonJS-like
module.exports = factory(require('./greeter.js'));
} else {
// Browser globals (root is window)
root.returnExports = factory(root.greeter);
}
}(this, function (greeter) {
greeter.sayHello("Daniel");
}));