Universal Module Definition (UMD)

Dec 01, 2020javascriptjs-modules

Since CommonJS (CJS) and Asynchronous Module Definition (AMD) styles have both been equally popular, it seems there’s yet no consensus. This has brought about the push for a universal pattern that supports both styles, which brings us to none other than the UMD.

The pattern is ugly, but is both AMD and CJS compatible, as well as supporting the old-style global variable definition.

// Uses AMD or browser globals to create a module.
;(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['b'], factory)
  } else {
    // Browser globals
    root.amdWeb = factory(root.b)
  }
})(typeof self !== 'undefined' ? self : this, function (b) {
  // Use b in some fashion.

  // 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 {}
})