0
# Configuration
1
2
Type-safe configuration utilities and loading mechanisms for managing complex build setups and development workflows. Rollup provides comprehensive configuration support including file loading, type helpers, and option merging.
3
4
## Capabilities
5
6
### DefineConfig Helper
7
8
Type helper function that provides IDE support and type checking for Rollup configuration files without affecting runtime behavior.
9
10
```typescript { .api }
11
/**
12
* Type helper for IDE support in configuration files
13
* @param options - Rollup configuration options
14
* @returns The same options with type information preserved
15
*/
16
function defineConfig<T extends RollupOptions | RollupOptions[] | RollupOptionsFunction>(
17
options: T
18
): T;
19
20
type RollupOptionsFunction = (
21
commandLineArguments: Record<string, any>
22
) => MaybePromise<RollupOptions | RollupOptions[]>;
23
```
24
25
**Usage Examples:**
26
27
```typescript
28
import { defineConfig } from "rollup";
29
30
// Single configuration
31
export default defineConfig({
32
input: "src/main.js",
33
output: {
34
file: "dist/bundle.js",
35
format: "esm"
36
}
37
});
38
39
// Multiple configurations
40
export default defineConfig([
41
{
42
input: "src/main.js",
43
output: { file: "dist/esm.js", format: "esm" }
44
},
45
{
46
input: "src/main.js",
47
output: { file: "dist/cjs.js", format: "cjs" }
48
}
49
]);
50
51
// Function-based configuration
52
export default defineConfig((commandLineArgs) => {
53
const isProduction = commandLineArgs.watch !== true;
54
55
return {
56
input: "src/main.js",
57
output: {
58
file: "dist/bundle.js",
59
format: "esm",
60
sourcemap: !isProduction
61
},
62
plugins: isProduction ? [terser()] : []
63
};
64
});
65
```
66
67
### Config File Loading
68
69
Utility for loading and processing Rollup configuration files programmatically, with support for various file formats and command-line option merging.
70
71
```typescript { .api }
72
/**
73
* Loads and processes Rollup configuration files
74
* @param fileName - Path to configuration file
75
* @param commandOptions - Command-line options to merge
76
* @param watchMode - Whether running in watch mode
77
* @returns Promise resolving to processed configuration and warnings
78
*/
79
function loadConfigFile(
80
fileName: string,
81
commandOptions?: object,
82
watchMode?: boolean
83
): Promise<{
84
options: MergedRollupOptions[];
85
warnings: BatchWarnings;
86
}>;
87
88
interface MergedRollupOptions extends InputOptionsWithPlugins {
89
output: OutputOptions[];
90
}
91
92
interface BatchWarnings {
93
add: (warning: RollupLog) => void;
94
flush: () => void;
95
log: LoggingFunction;
96
}
97
```
98
99
**Usage Examples:**
100
101
```typescript
102
import { loadConfigFile } from "rollup/loadConfigFile";
103
104
// Load configuration file
105
const { options, warnings } = await loadConfigFile(
106
"./rollup.config.js",
107
{ format: "esm" }, // command options
108
false // not watch mode
109
);
110
111
// Process each configuration
112
for (const inputOptions of options) {
113
const bundle = await rollup(inputOptions);
114
115
for (const outputOptions of inputOptions.output) {
116
await bundle.write(outputOptions);
117
}
118
119
await bundle.close();
120
}
121
122
// Handle warnings
123
warnings.flush();
124
```
125
126
## Configuration Types
127
128
### RollupOptions
129
130
Main configuration interface extending InputOptions with optional output configuration.
131
132
```typescript { .api }
133
interface RollupOptions extends InputOptions {
134
/** Output configuration (can be array for multiple outputs) */
135
output?: OutputOptions | OutputOptions[];
136
}
137
```
138
139
### InputOptions Details
140
141
Comprehensive input configuration options for controlling bundle creation behavior.
142
143
```typescript { .api }
144
interface InputOptions {
145
/** Entry point(s) for bundling */
146
input?: InputOption;
147
/** External dependencies to exclude */
148
external?: ExternalOption;
149
/** Input processing plugins */
150
plugins?: InputPluginOption;
151
/** Build caching configuration */
152
cache?: boolean | RollupCache;
153
/** Tree-shaking options */
154
treeshake?: boolean | TreeshakingPreset | TreeshakingOptions;
155
/** Watch mode configuration */
156
watch?: WatcherOptions | false;
157
/** Logging configuration */
158
logLevel?: LogLevelOption;
159
onLog?: LogHandlerWithDefault;
160
/** @deprecated Use onLog instead */
161
onwarn?: WarningHandlerWithDefault;
162
/** Module context configuration */
163
context?: string;
164
moduleContext?: ((id: string) => string | null) | Record<string, string>;
165
/** File system abstraction */
166
fs?: RollupFsModule;
167
/** Experimental features */
168
experimentalCacheExpiry?: number;
169
experimentalLogSideEffects?: boolean;
170
/** External handling options */
171
makeAbsoluteExternalsRelative?: boolean | 'ifRelativeSource';
172
/** Performance options */
173
maxParallelFileOps?: number;
174
perf?: boolean;
175
/** Entry signature handling */
176
preserveEntrySignatures?: PreserveEntrySignaturesOption;
177
/** Symlink handling */
178
preserveSymlinks?: boolean;
179
/** Missing export handling */
180
shimMissingExports?: boolean;
181
/** Deprecation warnings */
182
strictDeprecations?: boolean;
183
/** JSX processing */
184
jsx?: false | JsxPreset | JsxOptions;
185
}
186
187
type InputOption = string | string[] | Record<string, string>;
188
type LogLevelOption = LogLevel | 'silent';
189
type PreserveEntrySignaturesOption = false | 'strict' | 'allow-extension' | 'exports-only';
190
```
191
192
### OutputOptions Details
193
194
Complete output configuration for controlling bundle generation and writing.
195
196
```typescript { .api }
197
interface OutputOptions {
198
/** Output format */
199
format?: ModuleFormat;
200
/** Single file output */
201
file?: string;
202
/** Multiple file output directory */
203
dir?: string;
204
/** Output processing plugins */
205
plugins?: OutputPluginOption;
206
207
/** Source map configuration */
208
sourcemap?: boolean | 'inline' | 'hidden';
209
sourcemapBaseUrl?: string;
210
sourcemapExcludeSources?: boolean;
211
sourcemapFile?: string;
212
sourcemapFileNames?: string | ((chunkInfo: PreRenderedChunk) => string);
213
sourcemapIgnoreList?: boolean | SourcemapIgnoreListOption;
214
sourcemapPathTransform?: SourcemapPathTransformOption;
215
sourcemapDebugIds?: boolean;
216
217
/** File naming */
218
entryFileNames?: string | ((chunkInfo: PreRenderedChunk) => string);
219
chunkFileNames?: string | ((chunkInfo: PreRenderedChunk) => string);
220
assetFileNames?: string | ((chunkInfo: PreRenderedAsset) => string);
221
222
/** Code generation */
223
banner?: string | AddonFunction;
224
footer?: string | AddonFunction;
225
intro?: string | AddonFunction;
226
outro?: string | AddonFunction;
227
compact?: boolean;
228
generatedCode?: GeneratedCodePreset | GeneratedCodeOptions;
229
230
/** Module configuration */
231
exports?: 'default' | 'named' | 'none' | 'auto';
232
esModule?: boolean | 'if-default-prop';
233
externalLiveBindings?: boolean;
234
freeze?: boolean;
235
indent?: string | boolean;
236
inlineDynamicImports?: boolean;
237
interop?: InteropType | GetInterop;
238
minifyInternalExports?: boolean;
239
strict?: boolean;
240
241
/** Format-specific options */
242
name?: string; // UMD/IIFE global name
243
globals?: GlobalsOption;
244
extend?: boolean; // UMD extend existing global
245
noConflict?: boolean; // UMD noConflict mode
246
amd?: AmdOptions;
247
systemNullSetters?: boolean;
248
249
/** Chunking */
250
manualChunks?: ManualChunksOption;
251
experimentalMinChunkSize?: number;
252
253
/** Advanced options */
254
paths?: OptionsPaths;
255
preserveModules?: boolean;
256
preserveModulesRoot?: string;
257
hoistTransitiveImports?: boolean;
258
importAttributesKey?: ImportAttributesKey;
259
externalImportAttributes?: boolean;
260
/** @deprecated Use externalImportAttributes */
261
externalImportAssertions?: boolean;
262
reexportProtoFromExternal?: boolean;
263
sanitizeFileName?: boolean | ((fileName: string) => string);
264
validate?: boolean;
265
virtualDirname?: string;
266
dynamicImportInCjs?: boolean;
267
hashCharacters?: HashCharacters;
268
}
269
270
type ModuleFormat = 'amd' | 'cjs' | 'es' | 'iife' | 'system' | 'umd' | 'commonjs' | 'esm' | 'module' | 'systemjs';
271
type HashCharacters = 'base64' | 'base36' | 'hex';
272
type ImportAttributesKey = 'with' | 'assert';
273
```
274
275
### Tree-shaking Configuration
276
277
Advanced tree-shaking configuration for fine-tuning dead code elimination.
278
279
```typescript { .api }
280
interface TreeshakingOptions extends Partial<Omit<NormalizedTreeshakingOptions, 'moduleSideEffects'>> {
281
/** Module side effects configuration */
282
moduleSideEffects?: ModuleSideEffectsOption;
283
/** Preset configuration */
284
preset?: TreeshakingPreset;
285
}
286
287
interface NormalizedTreeshakingOptions {
288
/** Respect /*#__PURE__*/ annotations */
289
annotations: boolean;
290
/** Variable declaration hoisting behavior */
291
correctVarValueBeforeDeclaration: boolean;
292
/** Manual pure function annotations */
293
manualPureFunctions: readonly string[];
294
/** Module side effects detection */
295
moduleSideEffects: HasModuleSideEffects;
296
/** Property access side effects */
297
propertyReadSideEffects: boolean | 'always';
298
/** Try-catch deoptimization */
299
tryCatchDeoptimization: boolean;
300
/** Unknown global side effects */
301
unknownGlobalSideEffects: boolean;
302
}
303
304
type ModuleSideEffectsOption = boolean | 'no-external' | string[] | HasModuleSideEffects;
305
type TreeshakingPreset = 'smallest' | 'safest' | 'recommended';
306
type HasModuleSideEffects = (id: string, external: boolean) => boolean;
307
```
308
309
### Watch Configuration
310
311
File watching configuration for development workflows.
312
313
```typescript { .api }
314
interface WatcherOptions {
315
/** Allow input files inside output directory */
316
allowInputInsideOutputPath?: boolean;
317
/** Debounce delay for rebuilds */
318
buildDelay?: number;
319
/** Chokidar file watcher options */
320
chokidar?: ChokidarOptions;
321
/** Clear screen on rebuild */
322
clearScreen?: boolean;
323
/** Files to exclude from watching */
324
exclude?: string | RegExp | (string | RegExp)[];
325
/** Files to include in watching */
326
include?: string | RegExp | (string | RegExp)[];
327
/** Skip writing files (generate only) */
328
skipWrite?: boolean;
329
/** Callback for file invalidation */
330
onInvalidate?: (id: string) => void;
331
}
332
333
interface ChokidarOptions {
334
ignored?: any;
335
ignoreInitial?: boolean;
336
followSymlinks?: boolean;
337
cwd?: string;
338
disableGlobbing?: boolean;
339
usePolling?: boolean;
340
interval?: number;
341
binaryInterval?: number;
342
alwaysStat?: boolean;
343
depth?: number;
344
awaitWriteFinish?: boolean | { stabilityThreshold?: number; pollInterval?: number };
345
ignorePermissionErrors?: boolean;
346
atomic?: boolean | number;
347
persistent?: boolean;
348
useFsEvents?: boolean;
349
}
350
```
351
352
## Advanced Configuration Patterns
353
354
### Multi-Target Builds
355
356
```typescript
357
export default defineConfig([
358
// ES Module build
359
{
360
input: "src/index.ts",
361
external: ["react", "lodash"],
362
output: {
363
file: "dist/index.esm.js",
364
format: "esm",
365
sourcemap: true
366
},
367
plugins: [typescript()]
368
},
369
// CommonJS build
370
{
371
input: "src/index.ts",
372
external: ["react", "lodash"],
373
output: {
374
file: "dist/index.cjs.js",
375
format: "cjs",
376
exports: "named",
377
sourcemap: true
378
},
379
plugins: [typescript()]
380
},
381
// UMD build
382
{
383
input: "src/index.ts",
384
output: {
385
file: "dist/index.umd.js",
386
format: "umd",
387
name: "MyLibrary",
388
globals: {
389
react: "React",
390
lodash: "_"
391
}
392
},
393
plugins: [typescript(), resolve(), commonjs()]
394
}
395
]);
396
```
397
398
### Environment-based Configuration
399
400
```typescript
401
export default defineConfig((args) => {
402
const isProduction = !args.watch;
403
const isDevelopment = args.watch;
404
405
return {
406
input: "src/main.js",
407
output: {
408
file: "dist/bundle.js",
409
format: "esm",
410
sourcemap: isDevelopment
411
},
412
plugins: [
413
resolve(),
414
commonjs(),
415
...(isProduction ? [terser()] : []),
416
...(isDevelopment ? [livereload()] : [])
417
],
418
treeshake: isProduction ? "recommended" : false
419
};
420
});
421
```