Table of Contents

Javascript - Universal Module Definition (UMD)

About

The UMD module 1) format try to be the glue between differents modules definition by offering template 2)

A UMD module wraps the following module format:

You can the use UMD module in a AMD (requireJs), CommonJs (node) or Global Variable environment (browser)

Definition

UMD modules check for the existence of a module loader environment with the following code (where root is the global scope. It may be window)

Example from Template commonjsStrict.js:

(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 () {};
}));

At the top of the file, it’s almost always a UMD library when you see tests as:

D3

(function (global, factory) {
	typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
	typeof define === 'function' && define.amd ? define(['exports'], factory) :
	(factory((global.d3 = global.d3 || {})));
}(this, (function (exports) { 'use strict';

var version = "4.10.2";

// .........
// ........
exports.version;
exports.myFunction = myFunction;

Object.defineProperty(exports, '__esModule', { value: true });

})));

Documentation