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:

  • typeof define,
  • typeof window,
  • or typeof module

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





Discover More
Welcome From Browser
How to develop, publish and use a javascript library ?

A step by step tutorial on how to create and publish a javascript library
How to load a script dynamically with Javascript?

This page shows you how you can load a script dynamically with Javascript to load and use it when needed. In short, if you add: a script via an DOM element, it will be executed (via append or insertAdjacentElement)...
Javascript - Asynchronous Module Definition (AMD)

The AMD specifies a mechanism for defining modules such that: the module and its dependencies can be specified and loaded asynchronously. ie Both the module and dependencies can be asynchronously...
Javascript - Module

functionality in Javascript. A module is different from a script file because: it defines a well-scoped object that does not pollute the global namespace. It list explicitly its dependencies Javascript...
What is RequireJs: the browser module loader ?

RequireJs is a browser module loader that implements the AMD specification . It may load also other modules (UMD, CommonJs) In this example, we will load the bowser...



Share this page:
Follow us:
Task Runner