UMD Module Declarations
You'll learn: How to write type declarations for libraries that work seamlessly in both browser globals, CommonJS, and AMD environments.
What Are UMD Libraries?
UMD (Universal Module Definition) is a pattern that allows JavaScript libraries to work in multiple environments: as a browser global (via <script> tags), with CommonJS (Node.js require), and with AMD loaders. Popular libraries like jQuery, Lodash, and Moment.js historically shipped as UMD bundles to maximize compatibility.
When writing TypeScript declarations for these libraries, you need to describe this dual nature: the library exists both as a callable module and as a global variable.
The Basic UMD Declaration Pattern
A UMD declaration typically uses both an ambient module declaration and a global namespace declaration:
// mylib.d.ts
// ES6/CommonJS import support
export as namespace MyLib;
// The actual module exports
export function doSomething(value: string): number;
export const version: string;
// Types that consumers can use
export interface Config {
timeout: number;
retries: number;
}
The magic line export as namespace MyLib; tells TypeScript: "This module can also be accessed as a global variable named MyLib."
How Consumers Use It
With this declaration, the library works in multiple ways:
As an ES6/CommonJS import:
import * as MyLib from 'mylib';
MyLib.doSomething("hello");
As a browser global (no import needed):
// After <script src="mylib.js"></script>
MyLib.doSomething("hello");
Think of it like a restaurant with both dine-in and takeout: the same menu (type definitions) works for customers whether they consume on-site (global) or take it home (module import).
When You Need UMD Declarations
You'll write UMD declarations when:
- Creating types for legacy libraries that support multiple module systems
- Maintaining backwards compatibility with browser
<script>tag usage - Working with libraries designed before ES modules became standard
Key Takeaway: UMD declarations use export as namespace to declare that a module can be accessed both through imports and as a global variable, providing type safety for libraries that work in multiple environments.