0
# Core Compilation System
1
2
The core compilation system is the heart of webpack, orchestrating the entire build process through the Compiler and Compilation classes. This system manages the build lifecycle, hooks, and coordination between all webpack components.
3
4
## Capabilities
5
6
### Main Webpack Function
7
8
The primary webpack function that creates and optionally runs compiler instances.
9
10
```javascript { .api }
11
/**
12
* Main webpack compilation function
13
* @param options - Webpack configuration object or array of configurations
14
* @param callback - Optional callback for handling compilation results
15
* @returns Compiler or MultiCompiler instance, or null if callback fails immediately
16
*/
17
function webpack(
18
options: Configuration | MultiConfiguration,
19
callback?: (err: Error | null, stats?: Stats | MultiStats) => void
20
): Compiler | MultiCompiler | null;
21
```
22
23
**Usage Examples:**
24
25
```javascript
26
const webpack = require("webpack");
27
28
// Callback-style usage
29
webpack(config, (err, stats) => {
30
if (err || stats.hasErrors()) {
31
console.error(err || stats.toString());
32
return;
33
}
34
console.log("Build completed successfully!");
35
});
36
37
// Get compiler instance without running
38
const compiler = webpack(config);
39
```
40
41
### Compiler Class
42
43
The main webpack compiler that orchestrates the build process and provides a hooks-based plugin system.
44
45
```javascript { .api }
46
class Compiler {
47
/** Webpack configuration options */
48
options: WebpackOptionsNormalized;
49
50
/** Input file system */
51
inputFileSystem: InputFileSystem;
52
53
/** Output file system */
54
outputFileSystem: OutputFileSystem;
55
56
/** Hooks for plugin integration */
57
hooks: CompilerHooks;
58
59
/** Current compilation context */
60
context: string;
61
62
/**
63
* Run a single build
64
* @param callback - Callback with error and stats
65
*/
66
run(callback: (err: Error | null, stats?: Stats) => void): void;
67
68
/**
69
* Start watching for file changes
70
* @param watchOptions - Watch configuration
71
* @param handler - Handler for each compilation
72
* @returns Watching instance
73
*/
74
watch(
75
watchOptions: WatchOptions,
76
handler: (err: Error | null, stats?: Stats) => void
77
): Watching;
78
79
/**
80
* Close the compiler and release resources
81
* @param callback - Completion callback
82
*/
83
close(callback: (err?: Error) => void): void;
84
85
/**
86
* Get webpack cache instance
87
* @param name - Cache name
88
* @returns Cache facade
89
*/
90
getCache(name: string): CacheFacade;
91
92
/**
93
* Get logger instance
94
* @param name - Logger name
95
* @returns Logger instance
96
*/
97
getLogger(name: string): WebpackLogger;
98
99
/**
100
* Create child compiler with modified options
101
* @param compilation - Parent compilation
102
* @param compilerName - Name for child compiler
103
* @param compilerIndex - Index for child compiler
104
* @returns Child compiler instance
105
*/
106
createChildCompiler(
107
compilation: Compilation,
108
compilerName: string,
109
compilerIndex?: number
110
): Compiler;
111
}
112
113
interface CompilerHooks {
114
/** Before the environment is prepared */
115
environment: SyncHook<[]>;
116
/** After the environment is prepared */
117
afterEnvironment: SyncHook<[]>;
118
/** Before plugins are initialized */
119
initialize: SyncHook<[]>;
120
/** Before running starts */
121
beforeRun: AsyncSeriesHook<[Compiler]>;
122
/** When running starts */
123
run: AsyncSeriesHook<[Compiler]>;
124
/** Before watching starts */
125
watchRun: AsyncSeriesHook<[Compiler]>;
126
/** Before compilation starts */
127
beforeCompile: AsyncSeriesHook<[CompilationParams]>;
128
/** When compilation starts */
129
compile: SyncHook<[CompilationParams]>;
130
/** This compilation instance */
131
thisCompilation: SyncHook<[Compilation, CompilationParams]>;
132
/** Any compilation instance */
133
compilation: SyncHook<[Compilation, CompilationParams]>;
134
/** After compilation completes */
135
afterCompile: AsyncSeriesHook<[Compilation]>;
136
/** Before emitting assets */
137
emit: AsyncSeriesHook<[Compilation]>;
138
/** After emitting assets */
139
afterEmit: AsyncSeriesHook<[Compilation]>;
140
/** When build completes */
141
done: AsyncSeriesHook<[Stats]>;
142
/** Build completed with errors */
143
failed: SyncHook<[Error]>;
144
/** Compilation invalidated */
145
invalid: SyncHook<[string | null, number]>;
146
/** Watch stopped */
147
watchClose: SyncHook<[]>;
148
}
149
```
150
151
**Usage Examples:**
152
153
```javascript
154
const webpack = require("webpack");
155
const config = require("./webpack.config.js");
156
157
const compiler = webpack(config);
158
159
// Add plugin via hooks
160
compiler.hooks.done.tap("MyPlugin", (stats) => {
161
console.log("Build completed!");
162
});
163
164
// Run single build
165
compiler.run((err, stats) => {
166
if (err) {
167
console.error(err);
168
return;
169
}
170
171
console.log(stats.toString({
172
colors: true,
173
modules: false,
174
chunks: false
175
}));
176
177
compiler.close((closeErr) => {
178
if (closeErr) console.error(closeErr);
179
});
180
});
181
```
182
183
### MultiCompiler Class
184
185
Manages multiple webpack compiler instances for parallel or sequential builds.
186
187
```javascript { .api }
188
class MultiCompiler {
189
/** Array of child compilers */
190
compilers: Compiler[];
191
192
/** Dependency relationships between compilers */
193
dependencies: WeakMap<Compiler, string[]>;
194
195
/** Hooks for multi-compiler events */
196
hooks: MultiCompilerHooks;
197
198
/**
199
* Constructor for MultiCompiler
200
* @param compilers - Array of compiler instances
201
* @param options - Multi-compiler options
202
*/
203
constructor(compilers: Compiler[], options?: MultiCompilerOptions);
204
205
/**
206
* Run all compilers
207
* @param callback - Callback with error and multi-stats
208
*/
209
run(callback: (err: Error | null, stats?: MultiStats) => void): void;
210
211
/**
212
* Watch all compilers
213
* @param watchOptions - Watch options for each compiler
214
* @param handler - Handler for compilation results
215
* @returns MultiWatching instance
216
*/
217
watch(
218
watchOptions: WatchOptions | WatchOptions[],
219
handler: (err: Error | null, stats?: MultiStats) => void
220
): MultiWatching;
221
222
/**
223
* Close all compilers
224
* @param callback - Completion callback
225
*/
226
close(callback: (err?: Error) => void): void;
227
228
/**
229
* Set dependencies between compilers
230
* @param compiler - Dependent compiler
231
* @param dependencies - Array of dependency names
232
*/
233
setDependencies(compiler: Compiler, dependencies: string[]): void;
234
235
/**
236
* Validate dependencies for circular references
237
*/
238
validateDependencies(): void;
239
240
/**
241
* Create normal module factory
242
* @returns Normal module factory instance
243
*/
244
createNormalModuleFactory(): NormalModuleFactory;
245
246
/**
247
* Create context module factory
248
* @returns Context module factory instance
249
*/
250
createContextModuleFactory(): ContextModuleFactory;
251
252
/**
253
* Create new compilation parameters
254
* @returns Compilation parameters
255
*/
256
newCompilationParams(): CompilationParams;
257
258
/**
259
* Create new compilation instance
260
* @param params - Compilation parameters
261
* @returns New compilation
262
*/
263
createCompilation(params?: CompilationParams): Compilation;
264
265
/**
266
* Create and initialize new compilation
267
* @param params - Compilation parameters
268
* @returns Initialized compilation
269
*/
270
newCompilation(params: CompilationParams): Compilation;
271
272
/**
273
* Emit assets to output file system
274
* @param compilation - Compilation with assets
275
* @param callback - Completion callback
276
*/
277
emitAssets(compilation: Compilation, callback: (err?: Error) => void): void;
278
279
/**
280
* Emit records file
281
* @param callback - Completion callback
282
*/
283
emitRecords(callback: (err?: Error) => void): void;
284
285
/**
286
* Read records file
287
* @param callback - Completion callback
288
*/
289
readRecords(callback: (err?: Error) => void): void;
290
291
/**
292
* Run compilation as child process
293
* @param compilation - Parent compilation
294
* @param compilerName - Child compiler name
295
* @param compilerIndex - Child compiler index
296
* @param outputOptions - Output options for child
297
* @param plugins - Plugins for child compiler
298
* @param callback - Completion callback
299
*/
300
runAsChild(
301
compilation: Compilation,
302
compilerName: string,
303
compilerIndex: number,
304
outputOptions: OutputNormalized,
305
plugins: WebpackPluginInstance[],
306
callback: (err?: Error, entries?: Chunk[], compilation?: Compilation) => void
307
): void;
308
309
/**
310
* Check if this is a child compiler
311
* @returns True if child compiler
312
*/
313
isChild(): boolean;
314
315
/**
316
* Purge input file system cache
317
*/
318
purgeInputFileSystem(): void;
319
}
320
321
interface MultiCompilerHooks {
322
/** Before any compiler runs */
323
done: SyncHook<[MultiStats]>;
324
/** Invalid event from any compiler */
325
invalid: MultiHook<SyncHook<[string | null, number]>>;
326
}
327
328
interface MultiCompilerOptions {
329
/** Parallelism limit for running compilers */
330
parallelism?: number;
331
}
332
```
333
334
### Compilation Class
335
336
Represents a single build process containing modules, chunks, and assets.
337
338
```javascript { .api }
339
class Compilation {
340
/** Parent compiler instance */
341
compiler: Compiler;
342
343
/** Compilation hooks for plugin integration */
344
hooks: CompilationHooks;
345
346
/** All modules in this compilation */
347
modules: Set<Module>;
348
349
/** All chunks generated */
350
chunks: Set<Chunk>;
351
352
/** Generated assets */
353
assets: Record<string, Asset>;
354
355
/** Additional asset information */
356
assetsInfo: Map<string, AssetInfo>;
357
358
/** Compilation errors */
359
errors: WebpackError[];
360
361
/** Compilation warnings */
362
warnings: WebpackError[];
363
364
/** Module graph for dependency tracking */
365
moduleGraph: ModuleGraph;
366
367
/** Chunk graph for chunk relationships */
368
chunkGraph: ChunkGraph;
369
370
/** Code generation results */
371
codeGenerationResults: CodeGenerationResults;
372
373
/**
374
* Add entry point to compilation
375
* @param context - Entry context
376
* @param dependency - Entry dependency
377
* @param options - Entry options
378
* @param callback - Completion callback
379
*/
380
addEntry(
381
context: string,
382
dependency: Dependency,
383
options: EntryOptions | string,
384
callback: (err?: Error | null, module?: Module) => void
385
): void;
386
387
/**
388
* Rebuild a specific module
389
* @param modules - Modules to rebuild
390
* @param callback - Completion callback
391
*/
392
rebuildModule(
393
modules: Module[],
394
callback: (err?: Error | null, module?: Module) => void
395
): void;
396
397
/**
398
* Create hash for compilation
399
* @returns Hash string
400
*/
401
createHash(): string;
402
403
/**
404
* Emit asset to output
405
* @param filename - Output filename
406
* @param source - Asset source
407
* @param assetInfo - Asset metadata
408
*/
409
emitAsset(filename: string, source: Source, assetInfo?: AssetInfo): void;
410
411
/**
412
* Update existing asset
413
* @param filename - Asset filename
414
* @param newSource - New source
415
* @param assetInfoUpdateFn - Function to update asset info
416
*/
417
updateAsset(
418
filename: string,
419
newSource: Source | ((source: Source) => Source),
420
assetInfoUpdateFn?: (assetInfo: AssetInfo) => AssetInfo
421
): void;
422
423
/**
424
* Delete asset from compilation
425
* @param filename - Asset filename
426
*/
427
deleteAsset(filename: string): void;
428
429
/**
430
* Get asset source
431
* @param filename - Asset filename
432
* @returns Asset source or undefined
433
*/
434
getAsset(filename: string): Asset | undefined;
435
436
/**
437
* Get logger for this compilation
438
* @param name - Logger name
439
* @returns Logger instance
440
*/
441
getLogger(name: string): WebpackLogger;
442
}
443
444
interface Asset {
445
/** Asset source */
446
source: Source;
447
/** Asset information */
448
info: AssetInfo;
449
}
450
451
interface AssetInfo {
452
/** Whether asset is development only */
453
development?: boolean;
454
/** Whether asset is hot update only */
455
hotModuleReplacement?: boolean;
456
/** Source filename if different */
457
sourceFilename?: string;
458
/** Asset size in bytes */
459
size?: number;
460
/** Whether asset is immutable */
461
immutable?: boolean;
462
/** Whether asset is minimized */
463
minimized?: boolean;
464
/** Related assets */
465
related?: Record<string, string | string[]>;
466
/** Chunk hash if asset is chunk-specific */
467
chunkhash?: string | string[];
468
/** Content hash */
469
contenthash?: string | string[];
470
/** Full hash */
471
fullhash?: string;
472
}
473
```
474
475
### Stats Classes
476
477
Statistics and information about compilation results.
478
479
```javascript { .api }
480
class Stats {
481
/** Compilation instance */
482
compilation: Compilation;
483
484
/**
485
* Constructor for Stats
486
* @param compilation - Compilation instance
487
*/
488
constructor(compilation: Compilation);
489
490
/**
491
* Check if compilation has errors
492
* @returns True if errors exist
493
*/
494
hasErrors(): boolean;
495
496
/**
497
* Check if compilation has warnings
498
* @returns True if warnings exist
499
*/
500
hasWarnings(): boolean;
501
502
/**
503
* Convert stats to string
504
* @param options - Formatting options
505
* @returns Formatted string
506
*/
507
toString(options?: StatsOptions): string;
508
509
/**
510
* Convert stats to JSON
511
* @param options - JSON options
512
* @returns Stats as JSON object
513
*/
514
toJson(options?: StatsOptions): StatsCompilation;
515
}
516
517
class MultiStats {
518
/** Array of child stats */
519
stats: Stats[];
520
521
/**
522
* Constructor for MultiStats
523
* @param stats - Array of stats instances
524
*/
525
constructor(stats: Stats[]);
526
527
/**
528
* Check if any compilation has errors
529
* @returns True if any errors exist
530
*/
531
hasErrors(): boolean;
532
533
/**
534
* Check if any compilation has warnings
535
* @returns True if any warnings exist
536
*/
537
hasWarnings(): boolean;
538
539
/**
540
* Convert multi-stats to string
541
* @param options - Formatting options
542
* @returns Formatted string
543
*/
544
toString(options?: MultiStatsOptions): string;
545
546
/**
547
* Convert multi-stats to JSON
548
* @param options - JSON options
549
* @returns Multi-stats as JSON object
550
*/
551
toJson(options?: MultiStatsOptions): { children: StatsCompilation[] };
552
}
553
```
554
555
### Watching System
556
557
File watching capabilities for development workflows.
558
559
```javascript { .api }
560
class Watching {
561
/** Associated compiler */
562
compiler: Compiler;
563
564
/** Watching options */
565
options: WatchOptions;
566
567
/** File system watcher */
568
watcher: any;
569
570
/**
571
* Close watching and cleanup
572
* @param callback - Completion callback
573
*/
574
close(callback?: () => void): void;
575
576
/**
577
* Invalidate current compilation
578
* @param filename - Optional filename that changed
579
*/
580
invalidate(filename?: string): void;
581
582
/**
583
* Suspend watching temporarily
584
*/
585
suspend(): void;
586
587
/**
588
* Resume watching after suspension
589
*/
590
resume(): void;
591
}
592
593
interface WatchOptions {
594
/** Delay before rebuilding after change */
595
aggregateTimeout?: number;
596
/** Enable polling for file changes */
597
poll?: boolean | number;
598
/** Files/directories to ignore */
599
ignored?: string | RegExp | string[] | ((path: string) => boolean);
600
/** Follow symbolic links */
601
followSymlinks?: boolean;
602
/** Use stdin to stop watching */
603
stdin?: boolean;
604
}
605
606
class MultiWatching {
607
/** Array of individual watching instances */
608
watchings: Watching[];
609
610
/** Multi-compiler instance */
611
compiler: MultiCompiler;
612
613
/**
614
* Close all watching instances
615
* @param callback - Completion callback
616
*/
617
close(callback?: () => void): void;
618
619
/**
620
* Invalidate all watching instances
621
*/
622
invalidate(): void;
623
624
/**
625
* Suspend all watching instances
626
*/
627
suspend(): void;
628
629
/**
630
* Resume all watching instances
631
*/
632
resume(): void;
633
}
634
```
635
636
## Common Types
637
638
```javascript { .api }
639
interface WebpackOptionsNormalized {
640
context: string;
641
entry: EntryNormalized;
642
mode: "development" | "production" | "none";
643
output: OutputNormalized;
644
module: ModuleOptionsNormalized;
645
resolve: ResolveOptionsNormalized;
646
plugins: WebpackPluginInstance[];
647
// ... additional normalized options
648
}
649
650
interface CompilationParams {
651
normalModuleFactory: NormalModuleFactory;
652
contextModuleFactory: ContextModuleFactory;
653
}
654
655
interface EntryOptions {
656
name?: string;
657
runtime?: string | false;
658
dependOn?: string | string[];
659
publicPath?: string;
660
chunkLoading?: ChunkLoadingType;
661
asyncChunks?: boolean;
662
wasmLoading?: WasmLoadingType;
663
library?: LibraryOptions;
664
}
665
```