gitmyhub

umd

JavaScript ★ 7.4k updated 1y ago

UMD (Universal Module Definition) patterns for JavaScript modules that work everywhere.

A collection of JavaScript code templates that wrap a library so it loads correctly in any environment, Node.js, browsers with script tags, or AMD loaders like RequireJS, from a single file.

JavaScriptsetup: easycomplexity 1/5

UMD stands for Universal Module Definition, and this repository is a collection of JavaScript code templates that solve a specific historical problem: JavaScript has had several incompatible systems for loading and sharing code between files, and a library written for one system would not work in another.

The main formats involved are AMD, which was used by browser-side script loaders like RequireJS; CommonJS, which is the format Node.js uses; and plain browser globals, where a library just attaches itself to the global window object. Before UMD, a library author who wanted their code to work in all three environments would have to ship three separate files. UMD is a pattern, written as a small wrapper around your module code, that detects which environment it is running in and adapts automatically. A single file can then load correctly whether someone is using RequireJS in a browser, importing it in Node, or just including it with a script tag.

The repository contains several template variations rather than one universal answer, because different types of modules have different needs. Some modules have no dependencies at all, some depend on jQuery, some have circular references between modules, and so on. Each variation is a separate file with comments explaining which situation it is meant for. A library author reads through the options and picks the one that fits their code.

Build tool plugins for Grunt, Gulp, and other systems are listed in the README, which can wrap your code in the appropriate UMD boilerplate automatically without you having to write the wrapper by hand.

This project is largely of historical interest today. The JavaScript ecosystem has since settled on ES modules as the standard format, supported natively by modern browsers and recent versions of Node.js. Tools like webpack, Rollup, and esbuild now handle cross-format compatibility. But UMD remains in wide use in older codebases and libraries that needed to support environments from before that standardization.

Where it fits