0
# Programmatic API
1
2
The microbundle programmatic API provides complete control over the bundling process for integration into build scripts, development tools, or other Node.js applications.
3
4
## Capabilities
5
6
### Main Bundler Function
7
8
Core bundling function that processes JavaScript modules and generates multiple output formats.
9
10
```javascript { .api }
11
/**
12
* Bundle JavaScript modules with zero configuration
13
* @param inputOptions - Configuration options for bundling
14
* @returns Promise resolving to build results with output message and optional watchers
15
*/
16
function microbundle(inputOptions: MicrobundleOptions): Promise<MicrobundleResult>;
17
```
18
19
**Usage Examples:**
20
21
```javascript
22
import microbundle from "microbundle";
23
24
// Basic build
25
const result = await microbundle({
26
entries: ["src/index.js"],
27
format: "esm,cjs",
28
output: "dist"
29
});
30
console.log(result.output);
31
32
// Development build with watch mode
33
const watchResult = await microbundle({
34
entries: ["src/index.js", "src/cli.js"],
35
format: "modern,esm,cjs,umd",
36
watch: true,
37
sourcemap: true,
38
onBuild: (event) => console.log("Build completed!"),
39
onError: (event) => console.error("Build failed:", event.error)
40
});
41
42
// Node.js library build
43
const nodeResult = await microbundle({
44
entries: ["src/server.js"],
45
format: "cjs",
46
target: "node",
47
compress: false,
48
external: "none"
49
});
50
```
51
52
### Input Options
53
54
Configuration object passed to the main microbundle function.
55
56
```typescript { .api }
57
interface MicrobundleOptions {
58
/** Entry module paths to bundle (default: auto-detected from package.json) */
59
entries?: string[];
60
61
/** Output formats as comma-separated string (default: "modern,esm,cjs,umd") */
62
format?: string;
63
64
/** Alternative property name for format */
65
formats?: string;
66
67
/** Output directory or file path (default: from package.json main/module fields) */
68
output?: string;
69
70
/** Enable watch mode for development (default: false) */
71
watch?: boolean;
72
73
/** Target environment: 'web' for browsers, 'node' for Node.js (default: 'web') */
74
target?: "web" | "node";
75
76
/** Enable/disable Terser compression (default: true for web, false for node) */
77
compress?: boolean;
78
79
/** Generate source maps: true, false, or 'inline' (default: true) */
80
sourcemap?: boolean | string;
81
82
/** Working directory (default: process.cwd()) */
83
cwd?: string;
84
85
/** External dependencies: 'none' or comma-separated module names */
86
external?: string;
87
88
/** Global variable mappings for UMD builds (e.g., 'react=React,jquery=$') */
89
globals?: string;
90
91
/** Build-time constant definitions (e.g., 'API_URL=https://api.example.com') */
92
define?: string;
93
94
/** Module import aliases (e.g., 'react=preact/compat') */
95
alias?: string;
96
97
/** Enforce undefined global context and add "use strict" */
98
strict?: boolean;
99
100
/** UMD global name (default: camelCase of package name) */
101
name?: string;
102
103
/** Show raw byte sizes instead of gzipped (default: false) */
104
raw?: boolean;
105
106
/** JSX pragma function (default: 'h') */
107
jsx?: string;
108
109
/** JSX fragment pragma (default: 'Fragment') */
110
jsxFragment?: string;
111
112
/** JSX import source for automatic JSX runtime */
113
jsxImportSource?: string;
114
115
/** Path to custom TypeScript configuration file */
116
tsconfig?: string;
117
118
/** Generate TypeScript declaration files (default: from package.json types field) */
119
generateTypes?: boolean;
120
121
/** CSS output mode: 'inline' or 'external' (default: 'external') */
122
css?: string;
123
124
/** CSS modules configuration string */
125
"css-modules"?: string;
126
127
/** Bundle web workers using off-main-thread plugin (default: false) */
128
workers?: boolean;
129
130
/** Generate bundle composition visualization (default: false) */
131
visualize?: boolean;
132
133
/** Output files using package.json main entries pattern (default: true) */
134
"pkg-main"?: boolean;
135
136
/** Watch mode start callback */
137
onStart?: (event: WatchEvent) => void;
138
139
/** Watch mode build completion callback */
140
onBuild?: (event: WatchEvent) => void;
141
142
/** Watch mode error callback */
143
onError?: (event: WatchEvent) => void;
144
}
145
```
146
147
### Build Result
148
149
Object returned by the microbundle function containing build information.
150
151
```typescript { .api }
152
interface MicrobundleResult {
153
/** Human-readable build output message with file sizes and paths */
154
output: string;
155
156
/** File watchers for watch mode (only present when watch: true) */
157
watchers?: Record<string, any>;
158
}
159
```
160
161
### Watch Events
162
163
Event objects passed to watch mode callbacks.
164
165
```typescript { .api }
166
interface WatchEvent {
167
/** Event code: 'START', 'BUNDLE_START', 'BUNDLE_END', 'END', 'ERROR' */
168
code: string;
169
170
/** Error object (only present for ERROR events) */
171
error?: Error;
172
173
/** Input file path (for BUNDLE_START and BUNDLE_END events) */
174
input?: string;
175
176
/** Output bundle information */
177
result?: any;
178
}
179
```
180
181
**Advanced Usage Examples:**
182
183
```javascript
184
import microbundle from "microbundle";
185
186
// Custom build pipeline
187
async function buildLibrary(inputPath, outputPath) {
188
return await microbundle({
189
entries: [inputPath],
190
output: outputPath,
191
format: "modern,esm,cjs",
192
compress: process.env.NODE_ENV === "production",
193
sourcemap: process.env.NODE_ENV !== "production",
194
onStart: () => console.log("Starting build..."),
195
onBuild: () => console.log("Build completed successfully"),
196
onError: (event) => {
197
console.error("Build failed:", event.error.message);
198
process.exit(1);
199
}
200
});
201
}
202
203
// Development server integration
204
async function startDevMode() {
205
const result = await microbundle({
206
entries: ["src/index.ts"],
207
format: "esm",
208
watch: true,
209
sourcemap: "inline",
210
compress: false,
211
onBuild: (event) => {
212
// Trigger browser reload or other dev server actions
213
notifyDevServer();
214
}
215
});
216
217
return result.watchers;
218
}
219
```
220
221
### Error Handling
222
223
The microbundle function can throw various types of errors:
224
225
```javascript
226
try {
227
const result = await microbundle(options);
228
console.log(result.output);
229
} catch (error) {
230
if (error.code === 'UNRESOLVED_IMPORT') {
231
console.error('Missing dependency:', error.message);
232
} else if (error.plugin) {
233
console.error(`${error.plugin} plugin error:`, error.message);
234
} else {
235
console.error('Build error:', error.message);
236
}
237
}
238
```
239
240
### TypeScript Integration
241
242
Microbundle provides excellent TypeScript support with automatic type generation:
243
244
```javascript
245
// Build TypeScript library with declarations
246
const result = await microbundle({
247
entries: ["src/index.ts"],
248
format: "esm,cjs",
249
generateTypes: true,
250
tsconfig: "tsconfig.build.json"
251
});
252
253
// Mixed JavaScript and TypeScript
254
const mixedResult = await microbundle({
255
entries: ["src/index.js", "src/types.ts"],
256
generateTypes: true // Will generate .d.ts files
257
});
258
```
259
260
### Configuration Merging
261
262
Microbundle automatically merges configuration from multiple sources in this order of precedence:
263
264
1. Command-line arguments (highest priority)
265
2. Direct function options
266
3. `publishConfig` from package.json
267
4. Standard package.json fields (lowest priority)
268
269
```javascript
270
// Example: publishConfig override
271
// package.json:
272
{
273
"main": "src/index.js", // Used in development
274
"publishConfig": {
275
"main": "dist/index.js" // Used by microbundle
276
}
277
}
278
```