0
# Module System
1
2
Webpack's module system is the foundation for dependency management, code organization, and build optimization. It provides a comprehensive architecture for representing modules, tracking dependencies, organizing chunks, and managing the relationships between all components in a webpack build.
3
4
## Capabilities
5
6
### Base Module Class
7
8
The abstract base class that defines the interface for all webpack modules.
9
10
```javascript { .api }
11
class Module {
12
/** Module type identifier */
13
type: string;
14
15
/** Module context (directory path) */
16
context: string;
17
18
/** Module layer (for advanced module organization) */
19
layer: string | null;
20
21
/** Module needs identifier flag */
22
needId: boolean;
23
24
/** Debug identifier for the module */
25
debugId: number;
26
27
/** Hash for module content */
28
hash: string | null;
29
30
/** Rendered hash for optimization */
31
renderedHash: string | null;
32
33
/** Build information and metadata */
34
buildInfo: Record<string, any>;
35
36
/** Build metadata */
37
buildMeta: Record<string, any>;
38
39
/** Factory metadata */
40
factoryMeta: Record<string, any>;
41
42
/**
43
* Get unique identifier for the module
44
* @param context - Module context information
45
* @returns Unique string identifier
46
*/
47
identifier(): string;
48
49
/**
50
* Get readable identifier for debugging
51
* @param requestShortener - Function to shorten request strings
52
* @returns Human-readable identifier
53
*/
54
readableIdentifier(requestShortener: RequestShortener): string;
55
56
/**
57
* Build the module from source
58
* @param options - Build options and context
59
* @param compilation - Current compilation instance
60
* @param resolver - Module resolver
61
* @param fs - File system interface
62
* @param callback - Completion callback
63
*/
64
build(
65
options: WebpackOptionsNormalized,
66
compilation: Compilation,
67
resolver: ResolverWithOptions,
68
fs: InputFileSystem,
69
callback: (err?: Error | null) => void
70
): void;
71
72
/**
73
* Get module size in bytes
74
* @param type - Source type to measure
75
* @returns Size in bytes
76
*/
77
size(type?: string): number;
78
79
/**
80
* Update hash with module content
81
* @param hash - Hash instance to update
82
* @param context - Hash update context
83
*/
84
updateHash(hash: Hash, context: UpdateHashContext): void;
85
}
86
```
87
88
**Usage Examples:**
89
90
```javascript
91
// Custom module implementation
92
class CustomModule extends Module {
93
constructor(resource) {
94
super("custom", resource);
95
this.resource = resource;
96
}
97
98
identifier() {
99
return `custom ${this.resource}`;
100
}
101
102
readableIdentifier(requestShortener) {
103
return `custom ${requestShortener(this.resource)}`;
104
}
105
106
size() {
107
return 42; // Custom size calculation
108
}
109
}
110
```
111
112
### NormalModule Class
113
114
Represents standard file-based modules that are processed through loaders.
115
116
```javascript { .api }
117
class NormalModule extends Module {
118
/** Module request string */
119
request: string;
120
121
/** User request (original import/require) */
122
userRequest: string;
123
124
/** Raw request before resolution */
125
rawRequest: string;
126
127
/** Resolved resource path */
128
resource: string;
129
130
/** Resource path with query and fragment */
131
resourceResolveData: ResourceResolveData;
132
133
/** Matched loaders for this module */
134
loaders: LoaderItem[];
135
136
/** Parser instance for this module */
137
parser: Parser;
138
139
/** Generator instance for code generation */
140
generator: Generator;
141
142
/** Source of the module */
143
_source: Source | null;
144
145
/** Source map for the module */
146
_sourceMap: SourceMap | null;
147
148
/**
149
* Create a new NormalModule
150
* @param options - Module creation options
151
*/
152
constructor(options: NormalModuleCreateData);
153
154
/**
155
* Get loaders with their options
156
* @param compilation - Current compilation
157
* @returns Array of loader configurations
158
*/
159
getCurrentLoader(compilation: Compilation): LoaderItem | null;
160
161
/**
162
* Create source for this module
163
* @param dependencyTemplates - Dependency templates
164
* @param runtimeTemplate - Runtime template
165
* @param type - Source type
166
* @returns Generated source
167
*/
168
source(
169
dependencyTemplates: DependencyTemplates,
170
runtimeTemplate: RuntimeTemplate,
171
type?: string
172
): Source;
173
174
/**
175
* Get original source from loaders
176
* @returns Original source
177
*/
178
originalSource(): Source | null;
179
}
180
```
181
182
**Usage Examples:**
183
184
```javascript
185
// Creating a NormalModule programmatically
186
const normalModule = new NormalModule({
187
type: "javascript/auto",
188
request: "babel-loader!./src/component.js",
189
userRequest: "./src/component.js",
190
rawRequest: "./src/component.js",
191
loaders: [{
192
loader: "babel-loader",
193
options: {}
194
}],
195
resource: "/path/to/src/component.js",
196
resourceResolveData: {},
197
context: "/path/to/project",
198
layer: null
199
});
200
```
201
202
### ExternalModule Class
203
204
Represents modules that are provided externally and should not be bundled.
205
206
```javascript { .api }
207
class ExternalModule extends Module {
208
/** External module request */
209
request: string;
210
211
/** External type (e.g., "var", "commonjs", "amd") */
212
externalType: string;
213
214
/** User request string */
215
userRequest: string;
216
217
/** Whether this is optional */
218
optional: boolean;
219
220
/**
221
* Create an external module
222
* @param request - External module identifier
223
* @param type - External module type
224
* @param userRequest - Original user request
225
*/
226
constructor(request: string, type: string, userRequest: string);
227
228
/**
229
* Get external item for code generation
230
* @param dependencyTemplates - Dependency templates
231
* @param runtimeTemplate - Runtime template
232
* @returns External item configuration
233
*/
234
getSourceForGlobalVariableExternal(
235
variableName: string,
236
type: string
237
): Source;
238
}
239
```
240
241
**Usage Examples:**
242
243
```javascript
244
// External module for React (not bundled)
245
const reactExternal = new ExternalModule(
246
"React",
247
"var",
248
"react"
249
);
250
251
// External CommonJS module
252
const lodashExternal = new ExternalModule(
253
"lodash",
254
"commonjs",
255
"lodash"
256
);
257
```
258
259
### DelegatedModule Class
260
261
Represents modules from DLL (Dynamic Link Library) references.
262
263
```javascript { .api }
264
class DelegatedModule extends Module {
265
/** Source request for the delegate */
266
sourceRequest: string;
267
268
/** Request in the delegated scope */
269
request: string;
270
271
/** Delegation scope */
272
delegationType: string;
273
274
/** User request string */
275
userRequest: string;
276
277
/** Original module reference */
278
originalRequest: string;
279
280
/**
281
* Create a delegated module
282
* @param sourceRequest - Source request string
283
* @param data - Delegation data
284
*/
285
constructor(sourceRequest: string, data: DelegatedModuleData);
286
287
/**
288
* Get delegated source
289
* @param dependencyTemplates - Dependency templates
290
* @param runtimeTemplate - Runtime template
291
* @returns Generated source
292
*/
293
source(
294
dependencyTemplates: DependencyTemplates,
295
runtimeTemplate: RuntimeTemplate
296
): Source;
297
}
298
```
299
300
**Usage Examples:**
301
302
```javascript
303
// DLL module reference
304
const dllModule = new DelegatedModule("dll-reference vendor", {
305
type: "require",
306
request: "./node_modules/react/index.js"
307
});
308
```
309
310
### RuntimeModule Class
311
312
Represents modules that contain webpack runtime code.
313
314
```javascript { .api }
315
class RuntimeModule extends Module {
316
/** Runtime module name */
317
name: string;
318
319
/** Stage for runtime module execution */
320
stage: number;
321
322
/** Whether this module is cacheable */
323
cacheable: boolean;
324
325
/** Fresh flag for cache invalidation */
326
fresh: boolean;
327
328
/**
329
* Create a runtime module
330
* @param name - Runtime module name
331
* @param stage - Execution stage
332
*/
333
constructor(name: string, stage?: number);
334
335
/**
336
* Generate runtime code
337
* @returns Runtime source code
338
*/
339
generate(): Source | null;
340
341
/**
342
* Get runtime requirements
343
* @returns Set of runtime requirements
344
*/
345
getGeneratedRuntimeRequirements(): ReadonlySet<string>;
346
347
/**
348
* Attach to chunk
349
* @param chunk - Target chunk
350
*/
351
attach(compilation: Compilation, chunk: Chunk, chunkGraph: ChunkGraph): void;
352
}
353
```
354
355
**Usage Examples:**
356
357
```javascript
358
// Custom runtime module
359
class CustomRuntimeModule extends RuntimeModule {
360
constructor() {
361
super("custom-runtime", 0);
362
}
363
364
generate() {
365
return new RawSource(`
366
// Custom runtime code
367
__webpack_require__.custom = function() {
368
return "custom functionality";
369
};
370
`);
371
}
372
}
373
```
374
375
### ModuleGraph Class
376
377
Manages the dependency graph between modules, tracking relationships and providing graph operations.
378
379
```javascript { .api }
380
class ModuleGraph {
381
/**
382
* Set parent module for a dependency
383
* @param dependency - The dependency
384
* @param parentModule - Parent module containing the dependency
385
*/
386
setParents(
387
dependency: Dependency,
388
parentModule: Module,
389
parentBlock?: DependenciesBlock
390
): void;
391
392
/**
393
* Get parent module of a dependency
394
* @param dependency - The dependency
395
* @returns Parent module or null
396
*/
397
getParentModule(dependency: Dependency): Module | null;
398
399
/**
400
* Set resolved module for a dependency
401
* @param originModule - Module containing the dependency
402
* @param dependency - The dependency
403
* @param module - Resolved target module
404
*/
405
setResolvedModule(
406
originModule: Module,
407
dependency: Dependency,
408
module: Module
409
): void;
410
411
/**
412
* Update module with new instance
413
* @param dependency - The dependency
414
* @param module - New module instance
415
*/
416
updateModule(dependency: Dependency, module: Module): void;
417
418
/**
419
* Remove connection between modules
420
* @param dependency - The dependency to remove
421
*/
422
removeConnection(dependency: Dependency): void;
423
424
/**
425
* Get module resolved by dependency
426
* @param dependency - The dependency
427
* @returns Resolved module or null
428
*/
429
getModule(dependency: Dependency): Module | null;
430
431
/**
432
* Get connection information
433
* @param dependency - The dependency
434
* @returns Connection details or undefined
435
*/
436
getConnection(dependency: Dependency): ModuleGraphConnection | undefined;
437
438
/**
439
* Get all outgoing connections from a module
440
* @param module - Source module
441
* @returns Iterable of connections
442
*/
443
getOutgoingConnections(module: Module): Iterable<ModuleGraphConnection>;
444
445
/**
446
* Get all incoming connections to a module
447
* @param module - Target module
448
* @returns Iterable of connections
449
*/
450
getIncomingConnections(module: Module): Iterable<ModuleGraphConnection>;
451
452
/**
453
* Get profile information for a module
454
* @param module - The module
455
* @returns Module profile or null
456
*/
457
getProfile(module: Module): ModuleProfile | null;
458
459
/**
460
* Set profile for a module
461
* @param module - The module
462
* @param profile - Profile information
463
*/
464
setProfile(module: Module, profile: ModuleProfile | null): void;
465
}
466
```
467
468
**Usage Examples:**
469
470
```javascript
471
// Working with module graph
472
const moduleGraph = compilation.moduleGraph;
473
474
// Get dependencies of a module
475
const connections = moduleGraph.getOutgoingConnections(module);
476
for (const connection of connections) {
477
console.log(`${module.identifier()} depends on ${connection.module.identifier()}`);
478
}
479
480
// Find modules that depend on a specific module
481
const incomingConnections = moduleGraph.getIncomingConnections(targetModule);
482
for (const connection of incomingConnections) {
483
console.log(`${connection.originModule.identifier()} uses ${targetModule.identifier()}`);
484
}
485
```
486
487
### ChunkGraph Class
488
489
Maps modules to chunks and manages chunk relationships and optimization.
490
491
```javascript { .api }
492
class ChunkGraph {
493
/**
494
* Connect chunk and module
495
* @param chunk - The chunk
496
* @param module - The module
497
*/
498
connectChunkAndModule(chunk: Chunk, module: Module): void;
499
500
/**
501
* Disconnect chunk and module
502
* @param chunk - The chunk
503
* @param module - The module
504
*/
505
disconnectChunkAndModule(chunk: Chunk, module: Module): void;
506
507
/**
508
* Disconnect chunk from all modules
509
* @param chunk - The chunk to disconnect
510
*/
511
disconnectChunk(chunk: Chunk): void;
512
513
/**
514
* Attach runtime modules to chunk
515
* @param chunk - Target chunk
516
* @param module - Runtime module to attach
517
*/
518
attachRuntimeModules(chunk: Chunk, modules: Iterable<RuntimeModule>): void;
519
520
/**
521
* Attach full hash modules to chunk
522
* @param chunk - Target chunk
523
* @param modules - Modules requiring full hash
524
*/
525
attachFullHashModules(chunk: Chunk, modules: Iterable<RuntimeModule>): void;
526
527
/**
528
* Replace module in chunk
529
* @param oldModule - Module to replace
530
* @param newModule - Replacement module
531
*/
532
replaceModule(oldModule: Module, newModule: Module): void;
533
534
/**
535
* Check if module is in chunk
536
* @param module - The module
537
* @param chunk - The chunk
538
* @returns True if module is in chunk
539
*/
540
isModuleInChunk(module: Module, chunk: Chunk): boolean;
541
542
/**
543
* Get modules in chunk
544
* @param chunk - The chunk
545
* @returns Iterable of modules
546
*/
547
getChunkModules(chunk: Chunk): Iterable<Module>;
548
549
/**
550
* Get ordered chunk modules
551
* @param chunk - The chunk
552
* @param comparator - Module comparison function
553
* @returns Ordered array of modules
554
*/
555
getOrderedChunkModules(
556
chunk: Chunk,
557
comparator: (a: Module, b: Module) => number
558
): Module[];
559
560
/**
561
* Get chunks containing module
562
* @param module - The module
563
* @returns Iterable of chunks
564
*/
565
getModuleChunks(module: Module): Iterable<Chunk>;
566
567
/**
568
* Get number of chunk modules
569
* @param chunk - The chunk
570
* @returns Module count
571
*/
572
getNumberOfChunkModules(chunk: Chunk): number;
573
574
/**
575
* Get chunk graph module
576
* @param module - The module
577
* @returns Chunk graph module data
578
*/
579
getChunkGraphModule(module: Module): ChunkGraphModule;
580
581
/**
582
* Get module ID in chunk
583
* @param module - The module
584
* @param chunk - The chunk
585
* @returns Module ID or null
586
*/
587
getModuleId(module: Module): string | number | null;
588
589
/**
590
* Set module ID
591
* @param module - The module
592
* @param id - ID to assign
593
*/
594
setModuleId(module: Module, id: string | number): void;
595
596
/**
597
* Get runtime requirements for chunk
598
* @param chunk - The chunk
599
* @returns Set of runtime requirements
600
*/
601
getChunkRuntimeRequirements(chunk: Chunk): ReadonlySet<string>;
602
603
/**
604
* Add chunk runtime requirements
605
* @param chunk - The chunk
606
* @param requirements - Runtime requirements to add
607
*/
608
addChunkRuntimeRequirements(
609
chunk: Chunk,
610
requirements: Iterable<string>
611
): void;
612
}
613
```
614
615
**Usage Examples:**
616
617
```javascript
618
// Working with chunk graph
619
const chunkGraph = compilation.chunkGraph;
620
621
// Add module to chunk
622
chunkGraph.connectChunkAndModule(chunk, module);
623
624
// Get all modules in a chunk
625
const modules = chunkGraph.getChunkModules(entryChunk);
626
for (const module of modules) {
627
console.log(`Chunk contains: ${module.identifier()}`);
628
}
629
630
// Find which chunks contain a module
631
const chunks = chunkGraph.getModuleChunks(module);
632
for (const chunk of chunks) {
633
console.log(`Module is in chunk: ${chunk.name || chunk.id}`);
634
}
635
```
636
637
### Chunk Class
638
639
Represents a bundle of modules that will be emitted as a single file.
640
641
```javascript { .api }
642
class Chunk {
643
/** Chunk identifier */
644
id: string | number | null;
645
646
/** Chunk IDs (can have multiple) */
647
ids: (string | number)[] | null;
648
649
/** Debug ID for development */
650
debugId: number;
651
652
/** Chunk name */
653
name: string | null;
654
655
/** ID name mapping */
656
idNameHints: Set<string>;
657
658
/** Whether chunk prevents integration */
659
preventIntegration: boolean;
660
661
/** Files generated by this chunk */
662
files: Set<string>;
663
664
/** Auxiliary files */
665
auxiliaryFiles: Set<string>;
666
667
/** Runtime requirements */
668
runtime: RuntimeSpec;
669
670
/** Chunk hash */
671
hash: string | null;
672
673
/** Content hash by type */
674
contentHash: Record<string, string>;
675
676
/** Rendered hash */
677
renderedHash: string | null;
678
679
/** Chunk reason for creation */
680
chunkReason: string | null;
681
682
/**
683
* Create a new chunk
684
* @param name - Optional chunk name
685
*/
686
constructor(name?: string);
687
688
/**
689
* Check if chunk has entry module
690
* @returns True if chunk is an entry chunk
691
*/
692
hasEntryModule(): boolean;
693
694
/**
695
* Add group to chunk
696
* @param chunkGroup - Chunk group to add
697
*/
698
addGroup(chunkGroup: ChunkGroup): void;
699
700
/**
701
* Remove group from chunk
702
* @param chunkGroup - Chunk group to remove
703
*/
704
removeGroup(chunkGroup: ChunkGroup): void;
705
706
/**
707
* Check if chunk is in group
708
* @param chunkGroup - Chunk group to check
709
* @returns True if chunk is in group
710
*/
711
isInGroup(chunkGroup: ChunkGroup): boolean;
712
713
/**
714
* Get number of groups
715
* @returns Group count
716
*/
717
getNumberOfGroups(): number;
718
719
/**
720
* Get all chunk groups
721
* @returns Iterable of chunk groups
722
*/
723
groupsIterable: Iterable<ChunkGroup>;
724
725
/**
726
* Compare chunks for sorting
727
* @param otherChunk - Chunk to compare with
728
* @returns Comparison result
729
*/
730
compareTo(otherChunk: Chunk): number;
731
732
/**
733
* Check if chunk contains module
734
* @param module - Module to check
735
* @returns True if chunk contains module
736
*/
737
containsModule(module: Module): boolean;
738
739
/**
740
* Get chunk modules
741
* @returns Iterable of modules
742
*/
743
modulesIterable: Iterable<Module>;
744
745
/**
746
* Get chunk size
747
* @param options - Size calculation options
748
* @returns Chunk size
749
*/
750
size(options?: ChunkSizeOptions): number;
751
752
/**
753
* Get integrated size
754
* @param otherChunk - Chunk to integrate with
755
* @param options - Size options
756
* @returns Integrated size
757
*/
758
integratedSize(otherChunk: Chunk, options: ChunkSizeOptions): number;
759
760
/**
761
* Check if chunk can be integrated
762
* @param otherChunk - Chunk to check integration with
763
* @returns True if chunks can be integrated
764
*/
765
canBeIntegrated(otherChunk: Chunk): boolean;
766
767
/**
768
* Integrate with other chunk
769
* @param otherChunk - Chunk to integrate
770
* @returns True if integration was successful
771
*/
772
integrate(otherChunk: Chunk): boolean;
773
774
/**
775
* Check if chunk can be initial
776
* @returns True if chunk can be initial
777
*/
778
canBeInitial(): boolean;
779
780
/**
781
* Check if chunk is only initial
782
* @returns True if chunk is only initial
783
*/
784
isOnlyInitial(): boolean;
785
786
/**
787
* Get chunk hash based on modules
788
* @param chunkGraph - Chunk graph instance
789
* @returns Chunk hash
790
*/
791
getChunkMaps(chunkGraph: ChunkGraph): ChunkMaps;
792
}
793
```
794
795
**Usage Examples:**
796
797
```javascript
798
// Create and configure a chunk
799
const chunk = new Chunk("my-chunk");
800
chunk.name = "vendor";
801
chunk.chunkReason = "split vendor code";
802
803
// Check chunk properties
804
if (chunk.hasEntryModule()) {
805
console.log("This is an entry chunk");
806
}
807
808
// Get chunk size
809
const sizeOptions = { chunkOverhead: 10000, entryChunkMultiplicator: 10 };
810
const size = chunk.size(sizeOptions);
811
console.log(`Chunk size: ${size} bytes`);
812
```
813
814
### ChunkGroup Class
815
816
Groups related chunks together for loading and optimization purposes.
817
818
```javascript { .api }
819
class ChunkGroup {
820
/** Group options */
821
groupDebugId: number;
822
823
/** Group options */
824
options: ChunkGroupOptions;
825
826
/** Chunks in this group */
827
_chunks: Chunk[];
828
829
/** Parent groups */
830
_parents: Set<ChunkGroup>;
831
832
/** Children groups */
833
_children: Set<ChunkGroup>;
834
835
/** Async chunks */
836
_asyncEntrypoints: Set<ChunkGroup>;
837
838
/** Block origins */
839
_origins: OriginRecord[];
840
841
/**
842
* Create chunk group
843
* @param options - Group configuration options
844
*/
845
constructor(options?: ChunkGroupOptions);
846
847
/**
848
* Add chunk to group
849
* @param chunk - Chunk to add
850
* @returns True if chunk was added
851
*/
852
insertChunk(chunk: Chunk, before?: Chunk): boolean;
853
854
/**
855
* Remove chunk from group
856
* @param chunk - Chunk to remove
857
* @returns True if chunk was removed
858
*/
859
removeChunk(chunk: Chunk): boolean;
860
861
/**
862
* Check if group is initial
863
* @returns True if initial group
864
*/
865
isInitial(): boolean;
866
867
/**
868
* Add child group
869
* @param child - Child group to add
870
* @returns True if child was added
871
*/
872
addChild(child: ChunkGroup): boolean;
873
874
/**
875
* Get children groups
876
* @returns Array of child groups
877
*/
878
getChildren(): ChunkGroup[];
879
880
/**
881
* Get parent groups
882
* @returns Array of parent groups
883
*/
884
getParents(): ChunkGroup[];
885
886
/**
887
* Add parent group
888
* @param parent - Parent group to add
889
* @returns True if parent was added
890
*/
891
addParent(parent: ChunkGroup): boolean;
892
893
/**
894
* Remove parent group
895
* @param parent - Parent group to remove
896
*/
897
removeParent(parent: ChunkGroup): void;
898
899
/**
900
* Remove child group
901
* @param child - Child group to remove
902
*/
903
removeChild(child: ChunkGroup): void;
904
905
/**
906
* Get all chunks in group
907
* @returns Array of chunks
908
*/
909
getChunks(): Chunk[];
910
911
/**
912
* Get number of chunks
913
* @returns Chunk count
914
*/
915
getNumberOfChunks(): number;
916
917
/**
918
* Check if group has chunk
919
* @param chunk - Chunk to check
920
* @returns True if group has chunk
921
*/
922
hasChunk(chunk: Chunk): boolean;
923
924
/**
925
* Compare chunk groups
926
* @param otherGroup - Group to compare with
927
* @returns Comparison result
928
*/
929
compareTo(otherGroup: ChunkGroup): number;
930
931
/**
932
* Get module pre order index
933
* @param module - Module to get index for
934
* @returns Pre order index
935
*/
936
getModulePreOrderIndex(module: Module): number | null;
937
938
/**
939
* Get module post order index
940
* @param module - Module to get index for
941
* @returns Post order index
942
*/
943
getModulePostOrderIndex(module: Module): number | null;
944
945
/**
946
* Set module pre order index
947
* @param module - Module to set index for
948
* @param index - Index value
949
*/
950
setModulePreOrderIndex(module: Module, index: number): boolean;
951
952
/**
953
* Set module post order index
954
* @param module - Module to set index for
955
* @param index - Index value
956
*/
957
setModulePostOrderIndex(module: Module, index: number): boolean;
958
}
959
```
960
961
**Usage Examples:**
962
963
```javascript
964
// Create chunk group for vendor libraries
965
const vendorGroup = new ChunkGroup({
966
name: "vendor"
967
});
968
969
// Add chunks to group
970
vendorGroup.insertChunk(vendorChunk);
971
vendorGroup.insertChunk(runtimeChunk);
972
973
// Set up parent-child relationships
974
vendorGroup.addChild(asyncGroup);
975
mainGroup.addChild(vendorGroup);
976
```
977
978
### Entrypoint Class
979
980
Special chunk group representing application entry points.
981
982
```javascript { .api }
983
class Entrypoint extends ChunkGroup {
984
/** Entry options */
985
options: EntrypointOptions;
986
987
/** Runtime chunk */
988
_runtimeChunk: Chunk | null;
989
990
/** Entry module */
991
_entrypointChunk: Chunk | null;
992
993
/**
994
* Create entrypoint
995
* @param options - Entry configuration
996
*/
997
constructor(options: EntrypointOptions);
998
999
/**
1000
* Check if this is an entrypoint
1001
* @returns Always true for Entrypoint
1002
*/
1003
isInitial(): boolean;
1004
1005
/**
1006
* Set runtime chunk
1007
* @param chunk - Runtime chunk
1008
*/
1009
setRuntimeChunk(chunk: Chunk): void;
1010
1011
/**
1012
* Get runtime chunk
1013
* @returns Runtime chunk or null
1014
*/
1015
getRuntimeChunk(): Chunk | null;
1016
1017
/**
1018
* Set entrypoint chunk
1019
* @param chunk - Entrypoint chunk
1020
*/
1021
setEntrypointChunk(chunk: Chunk): void;
1022
1023
/**
1024
* Get entrypoint chunk
1025
* @returns Entrypoint chunk or null
1026
*/
1027
getEntrypointChunk(): Chunk | null;
1028
1029
/**
1030
* Replace chunk in entrypoint
1031
* @param oldChunk - Chunk to replace
1032
* @param newChunk - Replacement chunk
1033
*/
1034
replaceChunk(oldChunk: Chunk, newChunk: Chunk): boolean;
1035
}
1036
```
1037
1038
**Usage Examples:**
1039
1040
```javascript
1041
// Create application entrypoint
1042
const mainEntry = new Entrypoint({
1043
name: "main"
1044
});
1045
1046
// Set up entry and runtime chunks
1047
mainEntry.setEntrypointChunk(entryChunk);
1048
mainEntry.setRuntimeChunk(runtimeChunk);
1049
1050
// Add to compilation
1051
compilation.entrypoints.set("main", mainEntry);
1052
```
1053
1054
### Dependency System
1055
1056
#### Base Dependency Class
1057
1058
Abstract base class for all module dependencies.
1059
1060
```javascript { .api }
1061
class Dependency {
1062
/** Dependency type */
1063
type: string;
1064
1065
/** Category for grouping */
1066
category: string;
1067
1068
/** Location in source code */
1069
loc: SourceLocation | null;
1070
1071
/** Weak dependency flag */
1072
weak: boolean;
1073
1074
/** Optional dependency flag */
1075
optional: boolean;
1076
1077
/**
1078
* Get dependency type
1079
* @returns Dependency type string
1080
*/
1081
getType(): string;
1082
1083
/**
1084
* Get dependency category
1085
* @returns Category string
1086
*/
1087
getCategory(): string;
1088
1089
/**
1090
* Get reference exports
1091
* @param moduleGraph - Module graph instance
1092
* @param runtime - Runtime information
1093
* @returns Export references
1094
*/
1095
getReferencedExports(
1096
moduleGraph: ModuleGraph,
1097
runtime: RuntimeSpec
1098
): (string[] | ReferencedExport)[] | null;
1099
1100
/**
1101
* Get resource identifier
1102
* @returns Resource identifier or null
1103
*/
1104
getResourceIdentifier(): string | null;
1105
1106
/**
1107
* Get module evaluation side effects
1108
* @param moduleGraph - Module graph instance
1109
* @returns Side effects flag
1110
*/
1111
getModuleEvaluationSideEffectsState(
1112
moduleGraph: ModuleGraph
1113
): ConnectionState;
1114
1115
/**
1116
* Create hash of dependency
1117
* @param hash - Hash instance
1118
*/
1119
updateHash(hash: Hash): void;
1120
1121
/**
1122
* Serialize dependency
1123
* @param context - Serialization context
1124
*/
1125
serialize(context: ObjectSerializerContext): void;
1126
1127
/**
1128
* Deserialize dependency
1129
* @param context - Deserialization context
1130
*/
1131
deserialize(context: ObjectDeserializerContext): void;
1132
}
1133
```
1134
1135
#### ModuleDependency Class
1136
1137
Dependency between modules with request resolution.
1138
1139
```javascript { .api }
1140
class ModuleDependency extends Dependency {
1141
/** Module request string */
1142
request: string;
1143
1144
/** User request (original) */
1145
userRequest: string;
1146
1147
/** Request range in source */
1148
range: [number, number] | null;
1149
1150
/**
1151
* Create module dependency
1152
* @param request - Module request string
1153
*/
1154
constructor(request: string);
1155
1156
/**
1157
* Get request string
1158
* @returns Request string
1159
*/
1160
getRequest(): string;
1161
1162
/**
1163
* Get condition for module evaluation
1164
* @param moduleGraph - Module graph instance
1165
* @returns Connection state
1166
*/
1167
getCondition(moduleGraph: ModuleGraph): ConnectionState | null;
1168
}
1169
```
1170
1171
#### HarmonyImportDependency Class
1172
1173
ES6 import/export dependencies for harmony modules.
1174
1175
```javascript { .api }
1176
class HarmonyImportDependency extends ModuleDependency {
1177
/** Import source range */
1178
sourceOrder: number;
1179
1180
/** Parser scope */
1181
parserScope: any;
1182
1183
/**
1184
* Create harmony import dependency
1185
* @param request - Import request
1186
* @param sourceOrder - Source order number
1187
* @param parserScope - Parser scope information
1188
*/
1189
constructor(request: string, sourceOrder: number, parserScope?: any);
1190
1191
/**
1192
* Get import variable
1193
* @returns Import variable name
1194
*/
1195
getImportVar(moduleGraph: ModuleGraph): string;
1196
1197
/**
1198
* Get imported module
1199
* @param moduleGraph - Module graph instance
1200
* @returns Imported module or null
1201
*/
1202
getImportedModule(moduleGraph: ModuleGraph): Module | null;
1203
}
1204
```
1205
1206
#### ConstDependency Class
1207
1208
Dependency on constant values that are replaced during compilation.
1209
1210
```javascript { .api }
1211
class ConstDependency extends Dependency {
1212
/** Expression to replace */
1213
expression: string;
1214
1215
/** Range to replace */
1216
range: [number, number] | null;
1217
1218
/** Runtime requirements */
1219
runtimeRequirements: Set<string> | null;
1220
1221
/**
1222
* Create const dependency
1223
* @param expression - Replacement expression
1224
* @param range - Source range to replace
1225
* @param runtimeRequirements - Runtime requirements
1226
*/
1227
constructor(
1228
expression: string,
1229
range?: [number, number] | null,
1230
runtimeRequirements?: string[]
1231
);
1232
1233
/**
1234
* Update hash with expression
1235
* @param hash - Hash instance
1236
*/
1237
updateHash(hash: Hash): void;
1238
}
1239
```
1240
1241
#### NullDependency Class
1242
1243
No-operation dependency used as placeholder.
1244
1245
```javascript { .api }
1246
class NullDependency extends Dependency {
1247
/**
1248
* Create null dependency
1249
*/
1250
constructor();
1251
1252
/**
1253
* Compare with other dependency
1254
* @param other - Other dependency
1255
* @returns True if equal
1256
*/
1257
compare(other: Dependency): boolean;
1258
}
1259
```
1260
1261
**Dependency Usage Examples:**
1262
1263
```javascript
1264
// Create module dependency
1265
const moduleDep = new ModuleDependency("./utils/helper");
1266
moduleDep.range = [10, 30]; // Character range in source
1267
1268
// ES6 import dependency
1269
const importDep = new HarmonyImportDependency(
1270
"./components/Button",
1271
0,
1272
parserScope
1273
);
1274
1275
// Constant replacement
1276
const constDep = new ConstDependency(
1277
'"production"',
1278
[45, 60],
1279
[RuntimeGlobals.require]
1280
);
1281
1282
// Add dependencies to module
1283
module.addDependency(moduleDep);
1284
module.addDependency(importDep);
1285
module.addDependency(constDep);
1286
```
1287
1288
### ModuleFactory System
1289
1290
#### ModuleFactory Base Class
1291
1292
Abstract base for creating modules from dependency requests.
1293
1294
```javascript { .api }
1295
class ModuleFactory {
1296
/**
1297
* Create module from dependency
1298
* @param data - Module creation data
1299
* @param callback - Completion callback
1300
*/
1301
create(
1302
data: ModuleFactoryCreateData,
1303
callback: (err?: Error, result?: ModuleFactoryResult) => void
1304
): void;
1305
}
1306
```
1307
1308
#### NormalModuleFactory Class
1309
1310
Factory for creating standard file-based modules.
1311
1312
```javascript { .api }
1313
class NormalModuleFactory extends ModuleFactory {
1314
/** Resolver for modules */
1315
resolverFactory: ResolverFactory;
1316
1317
/** Rule set for matching loaders */
1318
ruleSet: RuleSet;
1319
1320
/** Context for resolution */
1321
context: string;
1322
1323
/** File system interface */
1324
fs: InputFileSystem;
1325
1326
/** Factory hooks */
1327
hooks: NormalModuleFactoryHooks;
1328
1329
/**
1330
* Create normal module factory
1331
* @param options - Factory options
1332
*/
1333
constructor(options: NormalModuleFactoryOptions);
1334
1335
/**
1336
* Create module from request
1337
* @param data - Creation data including context and dependencies
1338
* @param callback - Module creation callback
1339
*/
1340
create(
1341
data: ModuleFactoryCreateData,
1342
callback: (err?: Error, result?: NormalModuleFactoryResult) => void
1343
): void;
1344
1345
/**
1346
* Resolve module request
1347
* @param contextInfo - Context information
1348
* @param context - Base context path
1349
* @param request - Module request string
1350
* @param resolveOptions - Resolution options
1351
* @param callback - Resolution callback
1352
*/
1353
resolveRequestArray(
1354
contextInfo: ModuleFactoryCreateDataContextInfo,
1355
context: string,
1356
request: string,
1357
resolveOptions: ResolveOptionsWithDependencyType,
1358
callback: (err?: Error, result?: any[]) => void
1359
): void;
1360
}
1361
```
1362
1363
#### ContextModuleFactory Class
1364
1365
Factory for creating context (directory) modules.
1366
1367
```javascript { .api }
1368
class ContextModuleFactory extends ModuleFactory {
1369
/** Resolver factory */
1370
resolverFactory: ResolverFactory;
1371
1372
/**
1373
* Create context module factory
1374
* @param resolverFactory - Resolver factory instance
1375
*/
1376
constructor(resolverFactory: ResolverFactory);
1377
1378
/**
1379
* Create context module
1380
* @param data - Context creation data
1381
* @param callback - Creation callback
1382
*/
1383
create(
1384
data: ModuleFactoryCreateData,
1385
callback: (err?: Error, result?: ContextModuleFactoryResult) => void
1386
): void;
1387
}
1388
```
1389
1390
**ModuleFactory Usage Examples:**
1391
1392
```javascript
1393
// Using normal module factory
1394
const normalModuleFactory = compilation.dependencyFactories.get(Dependency);
1395
1396
const createData = {
1397
contextInfo: {
1398
issuer: "/path/to/issuer.js"
1399
},
1400
context: "/path/to/context",
1401
dependencies: [dependency]
1402
};
1403
1404
normalModuleFactory.create(createData, (err, result) => {
1405
if (err) {
1406
console.error("Module creation failed:", err);
1407
return;
1408
}
1409
1410
const module = result.module;
1411
console.log("Created module:", module.identifier());
1412
});
1413
```
1414
1415
### Parser System
1416
1417
Base parser class for analyzing module source code and extracting dependencies.
1418
1419
```javascript { .api }
1420
class Parser {
1421
/**
1422
* Parse module source
1423
* @param source - Module source code
1424
* @param state - Parser state
1425
* @returns Parser result
1426
*/
1427
parse(source: string | Buffer, state: ParserState): ParserResult;
1428
}
1429
```
1430
1431
**Parser Usage Examples:**
1432
1433
```javascript
1434
// JavaScript parser extracts dependencies
1435
const parser = new JavascriptParser("auto");
1436
1437
// Parse result contains AST and dependencies
1438
const result = parser.parse(source, {
1439
current: normalModule,
1440
module: normalModule,
1441
compilation: compilation,
1442
options: compilation.options
1443
});
1444
```
1445
1446
### Generator System
1447
1448
Base generator class for creating output code from modules.
1449
1450
```javascript { .api }
1451
class Generator {
1452
/**
1453
* Generate code for module
1454
* @param module - Module to generate code for
1455
* @param generateContext - Generation context
1456
* @returns Generated source
1457
*/
1458
generate(module: Module, generateContext: GenerateContext): Source;
1459
1460
/**
1461
* Get concatenation bailout reason
1462
* @param module - Module to check
1463
* @param generateContext - Generation context
1464
* @returns Bailout reason or undefined
1465
*/
1466
getConcatenationBailoutReason(
1467
module: Module,
1468
generateContext: GenerateContext
1469
): string | undefined;
1470
1471
/**
1472
* Update hash with generator state
1473
* @param hash - Hash instance
1474
* @param generateContext - Generation context
1475
*/
1476
updateHash(hash: Hash, generateContext: GenerateContext): void;
1477
}
1478
```
1479
1480
**Generator Usage Examples:**
1481
1482
```javascript
1483
// JavaScript generator creates output code
1484
const generator = new JavascriptGenerator();
1485
1486
const source = generator.generate(module, {
1487
dependencyTemplates,
1488
runtimeTemplate,
1489
moduleGraph,
1490
chunkGraph,
1491
runtimeRequirements,
1492
runtime,
1493
type: "javascript"
1494
});
1495
```
1496
1497
### Module Types and Constants
1498
1499
Webpack defines various module types and constants for the module system.
1500
1501
```javascript { .api }
1502
// Module type constants
1503
const MODULE_TYPE = {
1504
JAVASCRIPT_AUTO: "javascript/auto",
1505
JAVASCRIPT_DYNAMIC: "javascript/dynamic",
1506
JAVASCRIPT_ESM: "javascript/esm",
1507
JSON: "json",
1508
WEBASSEMBLY_SYNC: "webassembly/sync",
1509
WEBASSEMBLY_ASYNC: "webassembly/async",
1510
ASSET_RESOURCE: "asset/resource",
1511
ASSET_INLINE: "asset/inline",
1512
ASSET: "asset",
1513
RUNTIME: "runtime"
1514
};
1515
1516
// Dependency categories
1517
const DEPENDENCY_CATEGORY = {
1518
ESM: "esm",
1519
COMMONJS: "commonjs",
1520
AMD: "amd",
1521
REQUIRE_CONTEXT: "require.context",
1522
WORKER: "worker",
1523
URL: "url"
1524
};
1525
1526
// Connection states for dependencies
1527
const CONNECTION_STATE = {
1528
BOOL_TRUE: true,
1529
BOOL_FALSE: false,
1530
CIRCULAR_CONNECTION: Symbol("circular connection"),
1531
TRANSITIVE_CONNECTION: Symbol("transitive connection")
1532
};
1533
```
1534
1535
## Integration Examples
1536
1537
### Creating a Custom Module System
1538
1539
```javascript
1540
// Custom module factory
1541
class CustomModuleFactory extends ModuleFactory {
1542
create(data, callback) {
1543
const { context, dependencies } = data;
1544
const dependency = dependencies[0];
1545
1546
// Create custom module based on request pattern
1547
if (dependency.request.startsWith("custom:")) {
1548
const module = new CustomModule(dependency.request);
1549
callback(null, { module });
1550
} else {
1551
callback(new Error("Invalid custom module request"));
1552
}
1553
}
1554
}
1555
1556
// Register factory in compilation
1557
compilation.dependencyFactories.set(CustomDependency, customModuleFactory);
1558
```
1559
1560
### Working with Module Graph
1561
1562
```javascript
1563
// Analyze module relationships
1564
function analyzeModuleGraph(compilation) {
1565
const moduleGraph = compilation.moduleGraph;
1566
const modules = compilation.modules;
1567
1568
const analysis = {
1569
totalModules: modules.size,
1570
circularDependencies: [],
1571
largestModules: [],
1572
dependencyDepth: new Map()
1573
};
1574
1575
// Find circular dependencies
1576
for (const module of modules) {
1577
const visited = new Set();
1578
if (hasCycle(module, moduleGraph, visited)) {
1579
analysis.circularDependencies.push(module);
1580
}
1581
}
1582
1583
// Calculate dependency depths
1584
for (const module of modules) {
1585
analysis.dependencyDepth.set(
1586
module,
1587
calculateDepth(module, moduleGraph)
1588
);
1589
}
1590
1591
return analysis;
1592
}
1593
1594
function hasCycle(module, moduleGraph, visited, path = new Set()) {
1595
if (path.has(module)) return true;
1596
if (visited.has(module)) return false;
1597
1598
visited.add(module);
1599
path.add(module);
1600
1601
const connections = moduleGraph.getOutgoingConnections(module);
1602
for (const connection of connections) {
1603
if (connection.module && hasCycle(connection.module, moduleGraph, visited, path)) {
1604
return true;
1605
}
1606
}
1607
1608
path.delete(module);
1609
return false;
1610
}
1611
```
1612
1613
### Chunk Organization
1614
1615
```javascript
1616
// Custom chunk splitting strategy
1617
class CustomChunkSplitter {
1618
apply(compiler) {
1619
compiler.hooks.compilation.tap("CustomChunkSplitter", (compilation) => {
1620
compilation.hooks.optimizeChunks.tap("CustomChunkSplitter", (chunks) => {
1621
const chunkGraph = compilation.chunkGraph;
1622
1623
// Split large chunks
1624
for (const chunk of chunks) {
1625
const modules = chunkGraph.getChunkModules(chunk);
1626
const moduleArray = Array.from(modules);
1627
1628
if (moduleArray.length > 50) {
1629
const newChunk = compilation.addChunk(`${chunk.name}-split`);
1630
const halfSize = Math.floor(moduleArray.length / 2);
1631
1632
// Move half the modules to new chunk
1633
for (let i = halfSize; i < moduleArray.length; i++) {
1634
chunkGraph.disconnectChunkAndModule(chunk, moduleArray[i]);
1635
chunkGraph.connectChunkAndModule(newChunk, moduleArray[i]);
1636
}
1637
}
1638
}
1639
});
1640
});
1641
}
1642
}
1643
```
1644
1645
### Runtime Module Creation
1646
1647
```javascript
1648
// Custom runtime functionality
1649
class CustomRuntimeModule extends RuntimeModule {
1650
constructor() {
1651
super("custom-loader", RuntimeModule.STAGE_NORMAL);
1652
}
1653
1654
generate() {
1655
return new RawSource(`
1656
// Custom runtime functionality
1657
__webpack_require__.customLoader = function(moduleId) {
1658
console.log('Loading module:', moduleId);
1659
return __webpack_require__(moduleId);
1660
};
1661
1662
// Add custom module cache
1663
__webpack_require__.customCache = Object.create(null);
1664
`);
1665
}
1666
1667
getGeneratedRuntimeRequirements() {
1668
return new Set([RuntimeGlobals.require, RuntimeGlobals.moduleCache]);
1669
}
1670
}
1671
1672
// Add to compilation
1673
compilation.addRuntimeModule(chunk, new CustomRuntimeModule());
1674
```
1675
1676
The webpack module system provides a comprehensive architecture for managing code organization, dependency tracking, and build optimization. Understanding these core classes and their relationships enables powerful customization of the webpack build process and creation of advanced tooling and plugins.