0
# Core Bundling
1
2
Primary bundling functionality for creating optimized JavaScript bundles from ES modules. Rollup's core bundling provides advanced tree-shaking, code splitting, and multiple output format support.
3
4
## Capabilities
5
6
### Rollup Function
7
8
Main bundling function that creates a bundle from input options and returns a build object for generating output.
9
10
```typescript { .api }
11
/**
12
* Creates a bundle from input options
13
* @param options - Input configuration for bundling
14
* @returns Promise resolving to RollupBuild object
15
*/
16
function rollup(options: RollupOptions): Promise<RollupBuild>;
17
18
interface RollupOptions extends InputOptions {
19
output?: OutputOptions | OutputOptions[];
20
}
21
```
22
23
**Usage Examples:**
24
25
```typescript
26
import { rollup } from "rollup";
27
28
// Basic bundling
29
const bundle = await rollup({
30
input: "src/main.js"
31
});
32
33
// With plugins and external dependencies
34
const bundle = await rollup({
35
input: "src/main.js",
36
external: ["lodash", "react"],
37
plugins: [
38
// Plugin instances
39
],
40
treeshake: {
41
moduleSideEffects: false
42
}
43
});
44
45
// Multiple inputs
46
const bundle = await rollup({
47
input: {
48
main: "src/main.js",
49
worker: "src/worker.js"
50
}
51
});
52
```
53
54
### RollupBuild Object
55
56
Build object returned by rollup() function, providing methods for generating and writing bundles.
57
58
```typescript { .api }
59
/**
60
* Build object for generating and writing bundles
61
*/
62
interface RollupBuild {
63
/** Build cache for performance optimization */
64
cache: RollupCache | undefined;
65
/** Whether build has been closed */
66
closed: boolean;
67
/** Files being watched by the build */
68
watchFiles: string[];
69
/** Generate bundle without writing to disk */
70
generate(outputOptions: OutputOptions): Promise<RollupOutput>;
71
/** Generate and write bundle to disk */
72
write(outputOptions: OutputOptions): Promise<RollupOutput>;
73
/** Close the build and clean up resources */
74
close(): Promise<void>;
75
/** Async disposal support */
76
[Symbol.asyncDispose](): Promise<void>;
77
/** Performance timing data (if perf option enabled) */
78
getTimings?(): SerializedTimings;
79
}
80
```
81
82
### Generate Method
83
84
Generates bundle in memory without writing to disk, useful for programmatic access to generated code.
85
86
```typescript { .api }
87
/**
88
* Generate bundle without writing to disk
89
* @param outputOptions - Output configuration
90
* @returns Promise resolving to generated bundle
91
*/
92
generate(outputOptions: OutputOptions): Promise<RollupOutput>;
93
```
94
95
**Usage Examples:**
96
97
```typescript
98
// Generate ES module bundle
99
const { output } = await bundle.generate({
100
format: "esm"
101
});
102
103
const [chunk] = output;
104
console.log(chunk.code); // Generated JavaScript code
105
106
// Generate multiple formats
107
const esmResult = await bundle.generate({
108
format: "esm",
109
sourcemap: true
110
});
111
112
const cjsResult = await bundle.generate({
113
format: "cjs",
114
exports: "named"
115
});
116
```
117
118
### Write Method
119
120
Generates and writes bundle to disk based on output configuration.
121
122
```typescript { .api }
123
/**
124
* Generate and write bundle to disk
125
* @param outputOptions - Output configuration including file paths
126
* @returns Promise resolving to written bundle information
127
*/
128
write(outputOptions: OutputOptions): Promise<RollupOutput>;
129
```
130
131
**Usage Examples:**
132
133
```typescript
134
// Write single file
135
await bundle.write({
136
format: "esm",
137
file: "dist/bundle.js",
138
sourcemap: true
139
});
140
141
// Write multiple files to directory
142
await bundle.write({
143
format: "esm",
144
dir: "dist",
145
entryFileNames: "[name].js",
146
chunkFileNames: "[name]-[hash].js"
147
});
148
149
// Write with additional options
150
await bundle.write({
151
format: "umd",
152
file: "dist/bundle.umd.js",
153
name: "MyLibrary",
154
globals: {
155
lodash: "_",
156
react: "React"
157
}
158
});
159
```
160
161
### Bundle Cleanup
162
163
Proper resource cleanup to prevent memory leaks in long-running processes.
164
165
```typescript { .api }
166
/**
167
* Close the build and clean up resources
168
* @returns Promise that resolves when cleanup is complete
169
*/
170
close(): Promise<void>;
171
172
/**
173
* Async disposal support for using with syntax
174
* @returns Promise that resolves when disposal is complete
175
*/
176
[Symbol.asyncDispose](): Promise<void>;
177
```
178
179
**Usage Examples:**
180
181
```typescript
182
// Manual cleanup
183
const bundle = await rollup(options);
184
try {
185
await bundle.write(outputOptions);
186
} finally {
187
await bundle.close();
188
}
189
190
// Using async disposal (Node.js 20+)
191
{
192
await using bundle = await rollup(options);
193
await bundle.write(outputOptions);
194
// Automatically disposed at end of block
195
}
196
```
197
198
### Performance Timing
199
200
Optional performance timing collection for build optimization analysis.
201
202
```typescript { .api }
203
/**
204
* Get performance timing data (only available if perf option enabled)
205
* @returns Timing data for different build phases
206
*/
207
getTimings?(): SerializedTimings;
208
209
type SerializedTimings = Record<string, [number, number, number]>;
210
```
211
212
**Usage Examples:**
213
214
```typescript
215
// Enable performance timing
216
const bundle = await rollup({
217
input: "src/main.js",
218
perf: true // Enable timing collection
219
});
220
221
// Generate bundle and get timing data
222
await bundle.write({
223
format: "esm",
224
file: "dist/bundle.js"
225
});
226
227
// Get timing information
228
if (bundle.getTimings) {
229
const timings = bundle.getTimings();
230
console.log('Build timings:', timings);
231
232
// Timings format: [self_time, total_time, start_time]
233
Object.entries(timings).forEach(([phase, [self, total, start]]) => {
234
console.log(`${phase}: ${self}ms self, ${total}ms total`);
235
});
236
}
237
238
await bundle.close();
239
```
240
241
## Core Input Options
242
243
```typescript { .api }
244
interface InputOptions {
245
/** Entry point(s) for bundling */
246
input?: InputOption;
247
/** External dependencies to exclude from bundle */
248
external?: ExternalOption;
249
/** Input plugins for processing */
250
plugins?: InputPluginOption;
251
/** Build caching options */
252
cache?: boolean | RollupCache;
253
/** Tree-shaking configuration */
254
treeshake?: boolean | TreeshakingPreset | TreeshakingOptions;
255
/** Logging configuration */
256
logLevel?: LogLevelOption;
257
onLog?: LogHandlerWithDefault;
258
/** Development context path */
259
context?: string;
260
/** File system abstraction */
261
fs?: RollupFsModule;
262
/** Module context functions */
263
moduleContext?: ((id: string) => string | null) | Record<string, string>;
264
/** Performance timing collection */
265
perf?: boolean;
266
/** Entry signature preservation */
267
preserveEntrySignatures?: PreserveEntrySignaturesOption;
268
/** Symlink handling */
269
preserveSymlinks?: boolean;
270
/** JSX processing options */
271
jsx?: false | JsxPreset | JsxOptions;
272
}
273
274
type InputOption = string | string[] | Record<string, string>;
275
type ExternalOption =
276
| (string | RegExp)[]
277
| string
278
| RegExp
279
| ((source: string, importer: string | undefined, isResolved: boolean) => boolean | null);
280
type TreeshakingPreset = 'smallest' | 'safest' | 'recommended';
281
```
282
283
## Core Output Options
284
285
```typescript { .api }
286
interface OutputOptions {
287
/** Output format */
288
format?: ModuleFormat;
289
/** Single file output path */
290
file?: string;
291
/** Directory for multiple files */
292
dir?: string;
293
/** Output plugins */
294
plugins?: OutputPluginOption;
295
/** Source map generation */
296
sourcemap?: boolean | 'inline' | 'hidden';
297
/** Global variable mappings for external dependencies */
298
globals?: GlobalsOption;
299
/** Code to prepend to bundle */
300
banner?: string | AddonFunction;
301
/** Code to append to bundle */
302
footer?: string | AddonFunction;
303
/** Code to prepend inside wrapper */
304
intro?: string | AddonFunction;
305
/** Code to append inside wrapper */
306
outro?: string | AddonFunction;
307
/** Export mode */
308
exports?: 'default' | 'named' | 'none' | 'auto';
309
/** UMD/IIFE global name */
310
name?: string;
311
/** Compact output */
312
compact?: boolean;
313
/** Generated code features */
314
generatedCode?: GeneratedCodePreset | GeneratedCodeOptions;
315
/** Manual chunk configuration */
316
manualChunks?: ManualChunksOption;
317
/** File naming patterns */
318
entryFileNames?: string | ((chunkInfo: PreRenderedChunk) => string);
319
chunkFileNames?: string | ((chunkInfo: PreRenderedChunk) => string);
320
assetFileNames?: string | ((assetInfo: PreRenderedAsset) => string);
321
}
322
323
type ModuleFormat = 'amd' | 'cjs' | 'es' | 'iife' | 'system' | 'umd' | 'commonjs' | 'esm' | 'module' | 'systemjs';
324
type GlobalsOption = Record<string, string> | ((name: string) => string);
325
type AddonFunction = (chunk: RenderedChunk) => string | Promise<string>;
326
```
327
328
## Output Types
329
330
```typescript { .api }
331
interface RollupOutput {
332
output: [OutputChunk, ...(OutputChunk | OutputAsset)[]];
333
}
334
335
interface OutputChunk extends RenderedChunk {
336
/** Generated JavaScript code */
337
code: string;
338
/** Source map if enabled */
339
map: SourceMap | null;
340
/** Source map file name */
341
sourcemapFileName: string | null;
342
/** Preliminary file name before final processing */
343
preliminaryFileName: string;
344
}
345
346
interface OutputAsset extends PreRenderedAsset {
347
/** Final file name */
348
fileName: string;
349
/** Whether asset needs code reference */
350
needsCodeReference: boolean;
351
}
352
353
interface RenderedChunk extends PreRenderedChunk {
354
/** Generated file name */
355
fileName: string;
356
/** Dynamic imports */
357
dynamicImports: string[];
358
/** Files that should be loaded before this chunk */
359
implicitlyLoadedBefore: string[];
360
/** Imported bindings per module */
361
importedBindings: Record<string, string[]>;
362
/** Import file names */
363
imports: string[];
364
/** Detailed module information */
365
modules: Record<string, RenderedModule>;
366
/** Referenced asset files */
367
referencedFiles: string[];
368
}
369
```