UMD Modules and Global Augmentation
What you'll learn: How to type libraries that work both as imported modules and as global variables, combining the best of both worlds.
What Are UMD Modules?
UMD (Universal Module Definition) is a pattern that allows JavaScript libraries to work in multiple environments: as a CommonJS module (Node.js), an AMD module (RequireJS), or as a global variable in a browser <script> tag.
Think of UMD like a universal adapter plug that works in any outlet worldwide. The same library can be used in different ways:
import $ from 'jquery'(module import)const $ = require('jquery')(CommonJS)- Just
$as a global (browser script tag)
The Declaration Challenge
When typing a UMD library, you need to support both patterns:
// As a module import
import * as MyLib from 'my-library';
MyLib.doSomething();
// As a global variable
declare const MyLib: typeof import('my-library');
MyLib.doSomething();
UMD Declaration Pattern
// my-library.d.ts
export as namespace MyLib;
export function doSomething(value: string): void;
export function calculate(a: number, b: number): number;
export interface Options {
debug?: boolean;
timeout?: number;
}
The export as namespace MyLib; line is the magic that enables global usage. It tells TypeScript: "These exports are also available globally as MyLib."
Global Augmentation for UMD
Sometimes you need to add properties to the global scope when a UMD library is loaded via script tag:
declare global {
interface Window {
MyLib: typeof import('my-library');
}
}
This combines declare global with the module structure, letting users access window.MyLib in browsers while still supporting import syntax.
When to Use This Pattern
Use UMD declarations and global augmentation when:
- Supporting legacy browser code alongside modern bundlers
- Typing jQuery, Lodash, or similar libraries with dual usage
- Building libraries that must work with or without a module system
Key Takeaway: UMD module declarations with export as namespace let you type libraries that work both as imports and as globals, while global augmentation extends the global scope when needed—essential for libraries bridging modern and legacy JavaScript worlds.