0
# Optimization System
1
2
Webpack's optimization system provides comprehensive tools for improving bundle size, runtime performance, and caching effectiveness. It includes automatic code splitting, tree shaking, module concatenation, content hashing, and advanced optimization strategies for both development and production environments.
3
4
## Capabilities
5
6
### OptimizationOptions Interface
7
8
The main optimization configuration interface controlling all optimization behaviors.
9
10
```javascript { .api }
11
interface OptimizationOptions {
12
/** Enable/disable minimization */
13
minimize?: boolean;
14
15
/** Minimizer plugins to use */
16
minimizer?: WebpackPluginInstance[];
17
18
/** Split chunks configuration */
19
splitChunks?: SplitChunksOptions | false;
20
21
/** Runtime chunk extraction */
22
runtimeChunk?: RuntimeChunkOptions;
23
24
/** Emit assets even with errors */
25
emitOnErrors?: boolean;
26
27
/** Module concatenation (scope hoisting) */
28
concatenateModules?: boolean;
29
30
/** Side effects detection mode */
31
sideEffects?: boolean | "flag";
32
33
/** Used exports detection (tree shaking) */
34
usedExports?: boolean | "global";
35
36
/** Provided exports detection */
37
providedExports?: boolean;
38
39
/** Flag included chunks optimization */
40
flagIncludedChunks?: boolean;
41
42
/** Module ID optimization strategy */
43
moduleIds?: ModuleIdsType;
44
45
/** Chunk ID optimization strategy */
46
chunkIds?: ChunkIdsType;
47
48
/** Remove available modules optimization */
49
removeAvailableModules?: boolean;
50
51
/** Remove empty chunks */
52
removeEmptyChunks?: boolean;
53
54
/** Merge duplicate chunks */
55
mergeDuplicateChunks?: boolean;
56
57
/** Mangle WASM imports */
58
mangleWasmImports?: boolean;
59
60
/** Portable records */
61
portableRecords?: boolean;
62
63
/** Real content hash generation */
64
realContentHash?: boolean;
65
66
/** Inner graph optimization */
67
innerGraph?: boolean;
68
69
/** Mangle exports */
70
mangleExports?: boolean | "deterministic" | "size";
71
72
/** Node.js environment detection */
73
nodeEnv?: string | false;
74
75
/** Check WASM types */
76
checkWasmTypes?: boolean;
77
}
78
79
/** Module ID optimization types */
80
type ModuleIdsType = "natural" | "named" | "deterministic" | "hashed" | "size" | false;
81
82
/** Chunk ID optimization types */
83
type ChunkIdsType = "natural" | "named" | "deterministic" | "size" | "total-size" | false;
84
```
85
86
**Usage Examples:**
87
88
```javascript
89
module.exports = {
90
optimization: {
91
// Production optimizations
92
minimize: true,
93
moduleIds: "deterministic",
94
chunkIds: "deterministic",
95
96
// Tree shaking
97
usedExports: true,
98
sideEffects: false,
99
100
// Advanced optimizations
101
concatenateModules: true,
102
innerGraph: true,
103
realContentHash: true,
104
105
// Code splitting
106
splitChunks: {
107
chunks: "all",
108
cacheGroups: {
109
vendor: {
110
test: /[\\/]node_modules[\\/]/,
111
name: "vendors",
112
chunks: "all"
113
}
114
}
115
},
116
117
// Runtime extraction
118
runtimeChunk: "single"
119
}
120
};
121
```
122
123
### SplitChunksPlugin
124
125
Automatically splits code into separate chunks for optimal loading and caching.
126
127
```javascript { .api }
128
class SplitChunksPlugin {
129
/**
130
* Creates new SplitChunksPlugin instance
131
* @param options - Split chunks configuration options
132
*/
133
constructor(options?: SplitChunksOptions);
134
135
/**
136
* Apply plugin to compiler
137
* @param compiler - Webpack compiler instance
138
*/
139
apply(compiler: Compiler): void;
140
}
141
142
interface SplitChunksOptions {
143
/** Which chunks to optimize */
144
chunks?: ChunksFilterType;
145
146
/** Minimum size before chunk is split */
147
minSize?: number;
148
149
/** Minimum size reduction required */
150
minSizeReduction?: number;
151
152
/** Minimum remaining size after split */
153
minRemainingSize?: number;
154
155
/** Maximum size hint for chunks */
156
maxSize?: number;
157
158
/** Maximum size for async chunks */
159
maxAsyncSize?: number;
160
161
/** Maximum size for initial chunks */
162
maxInitialSize?: number;
163
164
/** Maximum number of async requests */
165
maxAsyncRequests?: number;
166
167
/** Maximum number of initial requests */
168
maxInitialRequests?: number;
169
170
/** Size threshold for enforcing split */
171
enforceSizeThreshold?: number;
172
173
/** Delimiter for automatic naming */
174
automaticNameDelimiter?: string;
175
176
/** Cache groups configuration */
177
cacheGroups?: CacheGroupsOptions;
178
179
/** Default chunk name */
180
name?: string | false | SplitChunksNameFunction;
181
182
/** Chunk filename template */
183
filename?: string | SplitChunksFilenameFunction;
184
185
/** Hide path info in names */
186
hidePathInfo?: boolean;
187
188
/** Use used exports info */
189
usedExports?: boolean;
190
}
191
192
/** Chunks filter types */
193
type ChunksFilterType =
194
| "all"
195
| "async"
196
| "initial"
197
| ((chunk: Chunk) => boolean);
198
199
/** Cache groups configuration */
200
interface CacheGroupsOptions {
201
[key: string]: CacheGroup | false;
202
}
203
204
interface CacheGroup {
205
/** Test condition for modules */
206
test?: TestCondition;
207
208
/** Include condition for modules */
209
include?: TestCondition;
210
211
/** Exclude condition for modules */
212
exclude?: TestCondition;
213
214
/** Priority for cache group */
215
priority?: number;
216
217
/** Minimum chunks that must share module */
218
minChunks?: number;
219
220
/** Minimum size for cache group */
221
minSize?: number;
222
223
/** Maximum size for cache group */
224
maxSize?: number;
225
226
/** Minimum size reduction */
227
minSizeReduction?: number;
228
229
/** Maximum async size */
230
maxAsyncSize?: number;
231
232
/** Maximum initial size */
233
maxInitialSize?: number;
234
235
/** Enforce size threshold */
236
enforceSizeThreshold?: number;
237
238
/** Reuse existing chunk if possible */
239
reuseExistingChunk?: boolean;
240
241
/** Cache group name */
242
name?: string | false | ((module: Module, chunks: Chunk[], key: string) => string);
243
244
/** Filename template */
245
filename?: string | ((pathData: PathData) => string);
246
247
/** Chunks to include */
248
chunks?: ChunksFilterType;
249
250
/** Automatic name delimiter */
251
automaticNameDelimiter?: string;
252
253
/** Use used exports */
254
usedExports?: boolean;
255
256
/** ID hint for deterministic naming */
257
idHint?: string;
258
}
259
260
/** Test condition types */
261
type TestCondition = string | RegExp | ((module: Module) => boolean);
262
263
/** Split chunks name function */
264
type SplitChunksNameFunction = (
265
module?: Module,
266
chunks?: Chunk[],
267
cacheGroupKey?: string
268
) => string | undefined;
269
270
/** Split chunks filename function */
271
type SplitChunksFilenameFunction = (pathData: PathData) => string;
272
```
273
274
**Usage Examples:**
275
276
```javascript
277
module.exports = {
278
optimization: {
279
splitChunks: {
280
// Split all chunks including async and initial
281
chunks: "all",
282
283
// Minimum size before creating chunk (20KB)
284
minSize: 20000,
285
286
// Maximum size hint (244KB)
287
maxSize: 244000,
288
289
// Cache groups for different chunk types
290
cacheGroups: {
291
// Vendor libraries
292
vendor: {
293
test: /[\\/]node_modules[\\/]/,
294
name: "vendors",
295
priority: 10,
296
chunks: "all",
297
reuseExistingChunk: true
298
},
299
300
// React ecosystem
301
react: {
302
test: /[\\/]node_modules[\\/](react|react-dom)[\\/]/,
303
name: "react",
304
priority: 20,
305
chunks: "all"
306
},
307
308
// Common modules shared between entry points
309
common: {
310
name: "common",
311
minChunks: 2,
312
priority: 5,
313
chunks: "all",
314
reuseExistingChunk: true,
315
enforce: true
316
},
317
318
// Utility libraries
319
utils: {
320
test: /[\\/]src[\\/]utils[\\/]/,
321
name: "utils",
322
priority: 15,
323
chunks: "all"
324
},
325
326
// CSS chunks
327
styles: {
328
name: "styles",
329
test: /\.(css|scss|sass)$/,
330
chunks: "all",
331
priority: 1
332
}
333
}
334
}
335
}
336
};
337
338
// Advanced configuration with dynamic naming
339
module.exports = {
340
optimization: {
341
splitChunks: {
342
chunks: "all",
343
minSize: 10000,
344
maxSize: 200000,
345
346
cacheGroups: {
347
vendor: {
348
test: /[\\/]node_modules[\\/]/,
349
name(module, chunks, cacheGroupKey) {
350
const moduleFileName = module
351
.identifier()
352
.split("/")
353
.reduceRight((item) => item);
354
const allChunksNames = chunks.map((item) => item.name).join("~");
355
return `${cacheGroupKey}-${allChunksNames}-${moduleFileName}`;
356
},
357
chunks: "all"
358
}
359
}
360
}
361
}
362
};
363
```
364
365
### RuntimeChunkPlugin
366
367
Extracts webpack runtime code into separate chunks for better caching.
368
369
```javascript { .api }
370
class RuntimeChunkPlugin {
371
/**
372
* Creates new RuntimeChunkPlugin instance
373
* @param options - Runtime chunk options
374
*/
375
constructor(options?: RuntimeChunkPluginOptions);
376
377
/**
378
* Apply plugin to compiler
379
* @param compiler - Webpack compiler instance
380
*/
381
apply(compiler: Compiler): void;
382
}
383
384
interface RuntimeChunkPluginOptions {
385
/** Runtime chunk name or function */
386
name?: string | RuntimeChunkFunction;
387
}
388
389
/** Runtime chunk configuration types */
390
type RuntimeChunkOptions =
391
| "single"
392
| "multiple"
393
| boolean
394
| { name?: string | RuntimeChunkFunction };
395
396
/** Runtime chunk name function */
397
type RuntimeChunkFunction = (entrypoint: Entrypoint) => string;
398
```
399
400
**Usage Examples:**
401
402
```javascript
403
module.exports = {
404
optimization: {
405
// Single runtime chunk for all entry points
406
runtimeChunk: "single"
407
}
408
};
409
410
// Multiple runtime chunks (one per entry)
411
module.exports = {
412
optimization: {
413
runtimeChunk: "multiple"
414
}
415
};
416
417
// Custom runtime chunk naming
418
module.exports = {
419
optimization: {
420
runtimeChunk: {
421
name: (entrypoint) => `runtime-${entrypoint.name}`
422
}
423
}
424
};
425
426
// Using plugin directly
427
module.exports = {
428
plugins: [
429
new webpack.optimize.RuntimeChunkPlugin({
430
name: "manifest"
431
})
432
]
433
};
434
```
435
436
### ModuleConcatenationPlugin
437
438
Enables scope hoisting by concatenating modules into single scopes when possible.
439
440
```javascript { .api }
441
class ModuleConcatenationPlugin {
442
/**
443
* Creates new ModuleConcatenationPlugin instance
444
*/
445
constructor();
446
447
/**
448
* Apply plugin to compiler
449
* @param compiler - Webpack compiler instance
450
*/
451
apply(compiler: Compiler): void;
452
}
453
```
454
455
**Usage Examples:**
456
457
```javascript
458
module.exports = {
459
optimization: {
460
// Enable module concatenation (scope hoisting)
461
concatenateModules: true
462
}
463
};
464
465
// Using plugin directly
466
module.exports = {
467
plugins: [
468
new webpack.optimize.ModuleConcatenationPlugin()
469
]
470
};
471
472
// Production mode enables this automatically
473
module.exports = {
474
mode: "production" // Includes concatenateModules: true
475
};
476
```
477
478
### RealContentHashPlugin
479
480
Generates content-based hashes after optimization for accurate cache invalidation.
481
482
```javascript { .api }
483
class RealContentHashPlugin {
484
/**
485
* Creates new RealContentHashPlugin instance
486
* @param options - Real content hash options
487
*/
488
constructor(options?: RealContentHashPluginOptions);
489
490
/**
491
* Apply plugin to compiler
492
* @param compiler - Webpack compiler instance
493
*/
494
apply(compiler: Compiler): void;
495
}
496
497
interface RealContentHashPluginOptions {
498
/** Hash function to use */
499
hashFunction?: string;
500
501
/** Hash digest encoding */
502
hashDigest?: string;
503
}
504
```
505
506
**Usage Examples:**
507
508
```javascript
509
module.exports = {
510
optimization: {
511
// Enable real content hash
512
realContentHash: true
513
}
514
};
515
516
// Using plugin directly with custom options
517
module.exports = {
518
plugins: [
519
new webpack.optimize.RealContentHashPlugin({
520
hashFunction: "sha256",
521
hashDigest: "hex"
522
})
523
]
524
};
525
526
// Combine with content hash in output
527
module.exports = {
528
output: {
529
filename: "[name].[contenthash].js",
530
chunkFilename: "[name].[contenthash].chunk.js"
531
},
532
optimization: {
533
realContentHash: true
534
}
535
};
536
```
537
538
### AggressiveMergingPlugin
539
540
Merges chunks aggressively to reduce the number of requests.
541
542
```javascript { .api }
543
class AggressiveMergingPlugin {
544
/**
545
* Creates new AggressiveMergingPlugin instance
546
* @param options - Aggressive merging options
547
*/
548
constructor(options?: AggressiveMergingPluginOptions);
549
550
/**
551
* Apply plugin to compiler
552
* @param compiler - Webpack compiler instance
553
*/
554
apply(compiler: Compiler): void;
555
}
556
557
interface AggressiveMergingPluginOptions {
558
/** Minimum size reduction required for merge */
559
minSizeReduce?: number;
560
561
/** Move modules to parents */
562
moveToParents?: boolean;
563
}
564
```
565
566
**Usage Examples:**
567
568
```javascript
569
module.exports = {
570
plugins: [
571
new webpack.optimize.AggressiveMergingPlugin({
572
minSizeReduce: 1.5,
573
moveToParents: true
574
})
575
]
576
};
577
578
// Combine with other chunk optimizations
579
module.exports = {
580
optimization: {
581
splitChunks: {
582
chunks: "all",
583
maxInitialRequests: 3,
584
maxAsyncRequests: 5
585
}
586
},
587
plugins: [
588
new webpack.optimize.AggressiveMergingPlugin()
589
]
590
};
591
```
592
593
### LimitChunkCountPlugin
594
595
Controls the maximum number of chunks to prevent too many HTTP requests.
596
597
```javascript { .api }
598
class LimitChunkCountPlugin {
599
/**
600
* Creates new LimitChunkCountPlugin instance
601
* @param options - Chunk count limit options
602
*/
603
constructor(options?: LimitChunkCountPluginOptions);
604
605
/**
606
* Apply plugin to compiler
607
* @param compiler - Webpack compiler instance
608
*/
609
apply(compiler: Compiler): void;
610
}
611
612
interface LimitChunkCountPluginOptions {
613
/** Maximum number of chunks */
614
maxChunks: number;
615
}
616
```
617
618
**Usage Examples:**
619
620
```javascript
621
module.exports = {
622
plugins: [
623
new webpack.optimize.LimitChunkCountPlugin({
624
maxChunks: 5
625
})
626
]
627
};
628
629
// For HTTP/1.1 environments with request limits
630
module.exports = {
631
plugins: [
632
new webpack.optimize.LimitChunkCountPlugin({
633
maxChunks: 1 // Bundle everything into single chunk
634
})
635
]
636
};
637
638
// Balance between caching and request count
639
module.exports = {
640
optimization: {
641
splitChunks: {
642
chunks: "all"
643
}
644
},
645
plugins: [
646
new webpack.optimize.LimitChunkCountPlugin({
647
maxChunks: 10
648
})
649
]
650
};
651
```
652
653
### MinChunkSizePlugin
654
655
Ensures chunks meet minimum size requirements by merging small chunks.
656
657
```javascript { .api }
658
class MinChunkSizePlugin {
659
/**
660
* Creates new MinChunkSizePlugin instance
661
* @param options - Minimum chunk size options
662
*/
663
constructor(options?: MinChunkSizePluginOptions);
664
665
/**
666
* Apply plugin to compiler
667
* @param compiler - Webpack compiler instance
668
*/
669
apply(compiler: Compiler): void;
670
}
671
672
interface MinChunkSizePluginOptions {
673
/** Minimum chunk size in bytes */
674
minChunkSize: number;
675
}
676
```
677
678
**Usage Examples:**
679
680
```javascript
681
module.exports = {
682
plugins: [
683
new webpack.optimize.MinChunkSizePlugin({
684
minChunkSize: 10000 // 10KB minimum
685
})
686
]
687
};
688
689
// Prevent tiny chunks from code splitting
690
module.exports = {
691
optimization: {
692
splitChunks: {
693
chunks: "all",
694
minSize: 20000
695
}
696
},
697
plugins: [
698
new webpack.optimize.MinChunkSizePlugin({
699
minChunkSize: 15000
700
})
701
]
702
};
703
```
704
705
## Tree Shaking and Dead Code Elimination
706
707
Webpack's tree shaking capabilities remove unused exports and dead code for smaller bundles.
708
709
### Used Exports Detection
710
711
```javascript { .api }
712
interface UsedExportsOptions {
713
/** Enable used exports detection */
714
usedExports?: boolean | "global";
715
716
/** Side effects detection */
717
sideEffects?: boolean | "flag" | string[] | ((request: string) => boolean);
718
719
/** Provided exports detection */
720
providedExports?: boolean;
721
}
722
```
723
724
**Usage Examples:**
725
726
```javascript
727
module.exports = {
728
mode: "production", // Enables tree shaking by default
729
730
optimization: {
731
// Enable used exports detection
732
usedExports: true,
733
734
// Mark as side-effect free for better tree shaking
735
sideEffects: false,
736
737
// Detect provided exports
738
providedExports: true
739
}
740
};
741
742
// Package.json side effects configuration
743
{
744
"sideEffects": false // Mark entire package as side-effect free
745
}
746
747
// Or specify files with side effects
748
{
749
"sideEffects": [
750
"./src/polyfills.js",
751
"*.css"
752
]
753
}
754
755
// Module-level side effects configuration
756
module.exports = {
757
module: {
758
rules: [
759
{
760
test: /\.js$/,
761
sideEffects: false // Mark JavaScript files as side-effect free
762
},
763
{
764
test: /\.css$/,
765
sideEffects: true // CSS imports have side effects
766
}
767
]
768
}
769
};
770
```
771
772
### Inner Graph Optimization
773
774
Advanced optimization analyzing module internals for better tree shaking.
775
776
```javascript { .api }
777
interface InnerGraphOptions {
778
/** Enable inner graph optimization */
779
innerGraph?: boolean;
780
}
781
```
782
783
**Usage Examples:**
784
785
```javascript
786
module.exports = {
787
optimization: {
788
// Enable advanced tree shaking
789
innerGraph: true,
790
usedExports: true,
791
sideEffects: false
792
}
793
};
794
795
// Production mode enables this automatically
796
module.exports = {
797
mode: "production"
798
};
799
```
800
801
## Module and Chunk ID Optimization
802
803
Optimization strategies for module and chunk identifiers affecting caching and bundle size.
804
805
### Module ID Strategies
806
807
```javascript { .api }
808
interface ModuleIdOptions {
809
/** Module ID generation strategy */
810
moduleIds?: ModuleIdsType;
811
}
812
813
type ModuleIdsType =
814
| "natural" // Natural numbers in order
815
| "named" // Human readable names (development)
816
| "deterministic" // Deterministic short hashes (production)
817
| "hashed" // Full content hashes
818
| "size" // Sort by module size
819
| false; // No optimization
820
```
821
822
**Usage Examples:**
823
824
```javascript
825
module.exports = {
826
optimization: {
827
// Development: readable names for debugging
828
moduleIds: process.env.NODE_ENV === "development" ? "named" : "deterministic"
829
}
830
};
831
832
// Production: deterministic IDs for caching
833
module.exports = {
834
mode: "production",
835
optimization: {
836
moduleIds: "deterministic",
837
chunkIds: "deterministic"
838
}
839
};
840
```
841
842
### Chunk ID Strategies
843
844
```javascript { .api }
845
interface ChunkIdOptions {
846
/** Chunk ID generation strategy */
847
chunkIds?: ChunkIdsType;
848
}
849
850
type ChunkIdsType =
851
| "natural" // Natural numbers
852
| "named" // Human readable names
853
| "deterministic" // Deterministic short hashes
854
| "size" // Sort by chunk size
855
| "total-size" // Sort by total size including dependencies
856
| false; // No optimization
857
```
858
859
**Usage Examples:**
860
861
```javascript
862
module.exports = {
863
optimization: {
864
chunkIds: "deterministic"
865
}
866
};
867
868
// Size-based optimization for loading priority
869
module.exports = {
870
optimization: {
871
chunkIds: "total-size" // Load smaller chunks first
872
}
873
};
874
```
875
876
### ID Optimization Plugins
877
878
Direct plugin usage for advanced ID optimization scenarios.
879
880
```javascript { .api }
881
class DeterministicChunkIdsPlugin {
882
/**
883
* Creates deterministic chunk IDs plugin
884
* @param options - Plugin options
885
*/
886
constructor(options?: DeterministicIdsPluginOptions);
887
888
apply(compiler: Compiler): void;
889
}
890
891
class DeterministicModuleIdsPlugin {
892
/**
893
* Creates deterministic module IDs plugin
894
* @param options - Plugin options
895
*/
896
constructor(options?: DeterministicIdsPluginOptions);
897
898
apply(compiler: Compiler): void;
899
}
900
901
class NamedChunkIdsPlugin {
902
/**
903
* Creates named chunk IDs plugin for development
904
*/
905
constructor();
906
907
apply(compiler: Compiler): void;
908
}
909
910
class NamedModuleIdsPlugin {
911
/**
912
* Creates named module IDs plugin for development
913
*/
914
constructor();
915
916
apply(compiler: Compiler): void;
917
}
918
919
class HashedModuleIdsPlugin {
920
/**
921
* Creates hashed module IDs plugin
922
* @param options - Hashing options
923
*/
924
constructor(options?: HashedModuleIdsPluginOptions);
925
926
apply(compiler: Compiler): void;
927
}
928
929
interface DeterministicIdsPluginOptions {
930
/** Maximum ID length */
931
maxLength?: number;
932
933
/** Salt for hash generation */
934
salt?: string;
935
936
/** Context for relative paths */
937
context?: string;
938
}
939
940
interface HashedModuleIdsPluginOptions {
941
/** Hash function */
942
hashFunction?: string;
943
944
/** Hash digest */
945
hashDigest?: string;
946
947
/** Hash digest length */
948
hashDigestLength?: number;
949
}
950
```
951
952
**Usage Examples:**
953
954
```javascript
955
// Custom deterministic IDs with max length
956
module.exports = {
957
plugins: [
958
new webpack.ids.DeterministicChunkIdsPlugin({
959
maxLength: 5,
960
salt: "my-app"
961
}),
962
new webpack.ids.DeterministicModuleIdsPlugin({
963
maxLength: 10
964
})
965
]
966
};
967
968
// Development-friendly named IDs
969
module.exports = {
970
plugins: [
971
new webpack.ids.NamedChunkIdsPlugin(),
972
new webpack.ids.NamedModuleIdsPlugin()
973
]
974
};
975
976
// Content-based hashed IDs
977
module.exports = {
978
plugins: [
979
new webpack.ids.HashedModuleIdsPlugin({
980
hashFunction: "sha256",
981
hashDigest: "base64",
982
hashDigestLength: 8
983
})
984
]
985
};
986
```
987
988
## Minimization and Compression
989
990
Code minimization and compression strategies for production builds.
991
992
### Minimization Configuration
993
994
```javascript { .api }
995
interface MinimizationOptions {
996
/** Enable/disable minimization */
997
minimize?: boolean;
998
999
/** Array of minimizer plugins */
1000
minimizer?: WebpackPluginInstance[];
1001
}
1002
```
1003
1004
**Usage Examples:**
1005
1006
```javascript
1007
const TerserPlugin = require("terser-webpack-plugin");
1008
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
1009
1010
module.exports = {
1011
optimization: {
1012
minimize: true,
1013
minimizer: [
1014
// JavaScript minimization
1015
new TerserPlugin({
1016
terserOptions: {
1017
compress: {
1018
drop_console: true,
1019
drop_debugger: true,
1020
pure_funcs: ["console.log", "console.info"]
1021
},
1022
mangle: {
1023
safari10: true
1024
},
1025
output: {
1026
comments: false,
1027
ascii_only: true
1028
}
1029
},
1030
extractComments: false,
1031
parallel: true
1032
}),
1033
1034
// CSS minimization
1035
new CssMinimizerPlugin({
1036
minimizerOptions: {
1037
preset: [
1038
"default",
1039
{
1040
discardComments: { removeAll: true },
1041
normalizeWhitespace: true
1042
}
1043
]
1044
}
1045
})
1046
]
1047
}
1048
};
1049
1050
// Development minimization for testing
1051
module.exports = {
1052
optimization: {
1053
minimize: process.env.NODE_ENV === "production",
1054
minimizer: [
1055
new TerserPlugin({
1056
terserOptions: {
1057
compress: false,
1058
mangle: false,
1059
keep_fnames: true,
1060
keep_classnames: true
1061
}
1062
})
1063
]
1064
}
1065
};
1066
```
1067
1068
## Side Effects Handling
1069
1070
Proper side effects configuration for effective tree shaking.
1071
1072
### Side Effects Configuration
1073
1074
```javascript { .api }
1075
interface SideEffectsOptions {
1076
/** Side effects detection mode */
1077
sideEffects?: boolean | "flag" | string[] | SideEffectsFunction;
1078
}
1079
1080
type SideEffectsFunction = (request: string, context: string) => boolean;
1081
```
1082
1083
**Usage Examples:**
1084
1085
```javascript
1086
module.exports = {
1087
optimization: {
1088
sideEffects: false // Mark all modules as side-effect free
1089
}
1090
};
1091
1092
// Conditional side effects
1093
module.exports = {
1094
optimization: {
1095
sideEffects: (request) => {
1096
// CSS and polyfills have side effects
1097
return /\.(css|scss|sass)$/.test(request) ||
1098
request.includes("polyfill");
1099
}
1100
}
1101
};
1102
1103
// Array of side effect patterns
1104
module.exports = {
1105
optimization: {
1106
sideEffects: [
1107
"*.css",
1108
"*.scss",
1109
"./src/polyfills.js",
1110
"@babel/polyfill"
1111
]
1112
}
1113
};
1114
1115
// Module rule-level side effects
1116
module.exports = {
1117
module: {
1118
rules: [
1119
{
1120
test: /\.js$/,
1121
exclude: /node_modules/,
1122
use: "babel-loader",
1123
sideEffects: false
1124
},
1125
{
1126
test: /\.css$/,
1127
use: ["style-loader", "css-loader"],
1128
sideEffects: true
1129
}
1130
]
1131
}
1132
};
1133
```
1134
1135
## Performance Optimization Strategies
1136
1137
### Development Optimization
1138
1139
Configuration optimized for fast development builds and debugging.
1140
1141
```javascript
1142
module.exports = {
1143
mode: "development",
1144
1145
optimization: {
1146
// Disable optimization for faster builds
1147
minimize: false,
1148
1149
// Simple module/chunk IDs for debugging
1150
moduleIds: "named",
1151
chunkIds: "named",
1152
1153
// Basic code splitting for development
1154
splitChunks: {
1155
chunks: "async",
1156
cacheGroups: {
1157
vendor: {
1158
test: /[\\/]node_modules[\\/]/,
1159
name: "vendors",
1160
chunks: "all",
1161
priority: 10
1162
}
1163
}
1164
},
1165
1166
// Separate runtime for HMR
1167
runtimeChunk: "single",
1168
1169
// Remove available modules for faster rebuilds
1170
removeAvailableModules: false,
1171
1172
// Don't remove empty chunks for debugging
1173
removeEmptyChunks: false,
1174
1175
// Keep used exports info for tree shaking preview
1176
usedExports: true,
1177
sideEffects: false,
1178
1179
// Enable provided exports for better IntelliSense
1180
providedExports: true
1181
},
1182
1183
// Fast source maps for development
1184
devtool: "eval-cheap-module-source-map"
1185
};
1186
```
1187
1188
### Production Optimization
1189
1190
Configuration optimized for production bundle size and runtime performance.
1191
1192
```javascript
1193
const TerserPlugin = require("terser-webpack-plugin");
1194
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
1195
const CompressionPlugin = require("compression-webpack-plugin");
1196
1197
module.exports = {
1198
mode: "production",
1199
1200
optimization: {
1201
// Full minimization
1202
minimize: true,
1203
minimizer: [
1204
new TerserPlugin({
1205
terserOptions: {
1206
compress: {
1207
drop_console: true,
1208
drop_debugger: true,
1209
passes: 2,
1210
pure_funcs: ["console.log", "console.info", "console.debug"]
1211
},
1212
mangle: {
1213
safari10: true,
1214
properties: {
1215
regex: /^_/
1216
}
1217
}
1218
},
1219
parallel: true,
1220
extractComments: false
1221
}),
1222
new CssMinimizerPlugin()
1223
],
1224
1225
// Aggressive code splitting
1226
splitChunks: {
1227
chunks: "all",
1228
minSize: 20000,
1229
maxSize: 200000,
1230
minSizeReduction: 10000,
1231
maxAsyncRequests: 30,
1232
maxInitialRequests: 30,
1233
1234
cacheGroups: {
1235
// Framework code
1236
framework: {
1237
test: /[\\/]node_modules[\\/](react|react-dom|vue|angular)[\\/]/,
1238
name: "framework",
1239
priority: 40,
1240
chunks: "all"
1241
},
1242
1243
// Vendor libraries
1244
vendor: {
1245
test: /[\\/]node_modules[\\/]/,
1246
name: "vendors",
1247
priority: 20,
1248
chunks: "all",
1249
reuseExistingChunk: true
1250
},
1251
1252
// Common code
1253
common: {
1254
name: "common",
1255
minChunks: 2,
1256
priority: 10,
1257
chunks: "all",
1258
reuseExistingChunk: true
1259
}
1260
}
1261
},
1262
1263
// Runtime extraction
1264
runtimeChunk: "single",
1265
1266
// Deterministic IDs for caching
1267
moduleIds: "deterministic",
1268
chunkIds: "deterministic",
1269
1270
// Tree shaking
1271
usedExports: true,
1272
sideEffects: false,
1273
providedExports: true,
1274
1275
// Advanced optimizations
1276
concatenateModules: true,
1277
innerGraph: true,
1278
realContentHash: true,
1279
mangleExports: "deterministic",
1280
1281
// Remove optimizations
1282
removeAvailableModules: true,
1283
removeEmptyChunks: true,
1284
mergeDuplicateChunks: true,
1285
1286
// Flag optimizations
1287
flagIncludedChunks: true
1288
},
1289
1290
plugins: [
1291
// Gzip compression
1292
new CompressionPlugin({
1293
algorithm: "gzip",
1294
test: /\.(js|css|html|svg)$/,
1295
threshold: 8192,
1296
minRatio: 0.8
1297
}),
1298
1299
// Brotli compression
1300
new CompressionPlugin({
1301
filename: "[path][base].br",
1302
algorithm: "brotliCompress",
1303
test: /\.(js|css|html|svg)$/,
1304
compressionOptions: {
1305
level: 11
1306
},
1307
threshold: 8192,
1308
minRatio: 0.8
1309
}),
1310
1311
// Additional chunk optimization
1312
new webpack.optimize.LimitChunkCountPlugin({
1313
maxChunks: 10
1314
}),
1315
1316
new webpack.optimize.MinChunkSizePlugin({
1317
minChunkSize: 30000
1318
})
1319
]
1320
};
1321
```
1322
1323
### Library Optimization
1324
1325
Optimizations specific to library builds.
1326
1327
```javascript
1328
module.exports = {
1329
mode: "production",
1330
1331
optimization: {
1332
minimize: true,
1333
1334
// Don't split chunks for libraries
1335
splitChunks: {
1336
chunks: () => false
1337
},
1338
1339
// No runtime chunk for libraries
1340
runtimeChunk: false,
1341
1342
// Deterministic IDs for consistent builds
1343
moduleIds: "deterministic",
1344
1345
// Tree shaking for library exports
1346
usedExports: true,
1347
sideEffects: false,
1348
1349
// Module concatenation for smaller bundles
1350
concatenateModules: true
1351
},
1352
1353
// Externalize dependencies
1354
externals: {
1355
react: {
1356
commonjs: "react",
1357
commonjs2: "react",
1358
amd: "React",
1359
root: "React"
1360
},
1361
"react-dom": {
1362
commonjs: "react-dom",
1363
commonjs2: "react-dom",
1364
amd: "ReactDOM",
1365
root: "ReactDOM"
1366
}
1367
},
1368
1369
output: {
1370
library: {
1371
name: "MyLibrary",
1372
type: "umd"
1373
},
1374
globalObject: "this"
1375
}
1376
};
1377
```
1378
1379
### Micro-frontend Optimization
1380
1381
Optimizations for micro-frontend architectures with shared dependencies.
1382
1383
```javascript
1384
const ModuleFederationPlugin = require("@module-federation/webpack");
1385
1386
module.exports = {
1387
mode: "production",
1388
1389
optimization: {
1390
// Standard production optimizations
1391
minimize: true,
1392
splitChunks: {
1393
chunks: "async", // Don't split shared chunks
1394
cacheGroups: {
1395
vendor: false, // Disable vendor splitting for federation
1396
default: false
1397
}
1398
},
1399
1400
// Deterministic IDs for consistency across micro-frontends
1401
moduleIds: "deterministic",
1402
chunkIds: "deterministic"
1403
},
1404
1405
plugins: [
1406
new ModuleFederationPlugin({
1407
name: "shell",
1408
filename: "remoteEntry.js",
1409
1410
// Shared dependencies
1411
shared: {
1412
react: {
1413
singleton: true,
1414
eager: true,
1415
requiredVersion: "^17.0.0"
1416
},
1417
"react-dom": {
1418
singleton: true,
1419
eager: true,
1420
requiredVersion: "^17.0.0"
1421
}
1422
}
1423
})
1424
]
1425
};
1426
```
1427
1428
## Bundle Analysis and Optimization
1429
1430
Tools and techniques for analyzing and optimizing webpack bundles.
1431
1432
### Bundle Analysis Configuration
1433
1434
```javascript
1435
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPlugin;
1436
1437
module.exports = {
1438
plugins: [
1439
// Bundle size analysis
1440
new BundleAnalyzerPlugin({
1441
analyzerMode: process.env.ANALYZE ? "server" : "disabled",
1442
openAnalyzer: false,
1443
generateStatsFile: true,
1444
statsFilename: "bundle-stats.json"
1445
})
1446
],
1447
1448
// Performance budgets
1449
performance: {
1450
maxAssetSize: 250000,
1451
maxEntrypointSize: 250000,
1452
hints: "warning",
1453
1454
// Filter specific asset types
1455
assetFilter: (assetFilename) => {
1456
return assetFilename.endsWith('.js') || assetFilename.endsWith('.css');
1457
}
1458
}
1459
};
1460
```
1461
1462
### Optimization Monitoring
1463
1464
```javascript
1465
module.exports = {
1466
stats: {
1467
// Optimization information
1468
optimizationBailout: true,
1469
chunks: true,
1470
chunkModules: true,
1471
chunkOrigins: true,
1472
1473
// Performance metrics
1474
timings: true,
1475
builtAt: true,
1476
1477
// Tree shaking information
1478
usedExports: true,
1479
providedExports: true,
1480
1481
// Detailed module information
1482
modules: true,
1483
moduleTrace: true,
1484
reasons: true
1485
}
1486
};
1487
```
1488
1489
This comprehensive optimization documentation covers webpack's full optimization system, from basic configuration to advanced production strategies, providing developers with the tools to create highly optimized bundles for any use case.