UNPKG

26.3 kBJavaScriptView Raw
1/*
2 MIT License http://www.opensource.org/licenses/mit-license.php
3 Author Tobias Koppers @sokra
4*/
5
6"use strict";
7
8const OptionsApply = require("./OptionsApply");
9
10const AssetModulesPlugin = require("./asset/AssetModulesPlugin");
11const JavascriptModulesPlugin = require("./javascript/JavascriptModulesPlugin");
12const JsonModulesPlugin = require("./json/JsonModulesPlugin");
13
14const ChunkPrefetchPreloadPlugin = require("./prefetch/ChunkPrefetchPreloadPlugin");
15
16const EntryOptionPlugin = require("./EntryOptionPlugin");
17const RecordIdsPlugin = require("./RecordIdsPlugin");
18
19const RuntimePlugin = require("./RuntimePlugin");
20
21const APIPlugin = require("./APIPlugin");
22const CompatibilityPlugin = require("./CompatibilityPlugin");
23const ConstPlugin = require("./ConstPlugin");
24const ExportsInfoApiPlugin = require("./ExportsInfoApiPlugin");
25const WebpackIsIncludedPlugin = require("./WebpackIsIncludedPlugin");
26
27const TemplatedPathPlugin = require("./TemplatedPathPlugin");
28const UseStrictPlugin = require("./UseStrictPlugin");
29const WarnCaseSensitiveModulesPlugin = require("./WarnCaseSensitiveModulesPlugin");
30
31const DataUriPlugin = require("./schemes/DataUriPlugin");
32const FileUriPlugin = require("./schemes/FileUriPlugin");
33
34const ResolverCachePlugin = require("./cache/ResolverCachePlugin");
35
36const CommonJsPlugin = require("./dependencies/CommonJsPlugin");
37const HarmonyModulesPlugin = require("./dependencies/HarmonyModulesPlugin");
38const ImportMetaContextPlugin = require("./dependencies/ImportMetaContextPlugin");
39const ImportMetaPlugin = require("./dependencies/ImportMetaPlugin");
40const ImportPlugin = require("./dependencies/ImportPlugin");
41const LoaderPlugin = require("./dependencies/LoaderPlugin");
42const RequireContextPlugin = require("./dependencies/RequireContextPlugin");
43const RequireEnsurePlugin = require("./dependencies/RequireEnsurePlugin");
44const RequireIncludePlugin = require("./dependencies/RequireIncludePlugin");
45const SystemPlugin = require("./dependencies/SystemPlugin");
46const URLPlugin = require("./dependencies/URLPlugin");
47const WorkerPlugin = require("./dependencies/WorkerPlugin");
48
49const InferAsyncModulesPlugin = require("./async-modules/InferAsyncModulesPlugin");
50
51const JavascriptMetaInfoPlugin = require("./JavascriptMetaInfoPlugin");
52const DefaultStatsFactoryPlugin = require("./stats/DefaultStatsFactoryPlugin");
53const DefaultStatsPresetPlugin = require("./stats/DefaultStatsPresetPlugin");
54const DefaultStatsPrinterPlugin = require("./stats/DefaultStatsPrinterPlugin");
55
56const { cleverMerge } = require("./util/cleverMerge");
57
58/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */
59/** @typedef {import("./Compiler")} Compiler */
60
61class WebpackOptionsApply extends OptionsApply {
62 constructor() {
63 super();
64 }
65
66 /**
67 * @param {WebpackOptions} options options object
68 * @param {Compiler} compiler compiler object
69 * @returns {WebpackOptions} options object
70 */
71 process(options, compiler) {
72 compiler.outputPath = options.output.path;
73 compiler.recordsInputPath = options.recordsInputPath || null;
74 compiler.recordsOutputPath = options.recordsOutputPath || null;
75 compiler.name = options.name;
76
77 if (options.externals) {
78 //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
79 const ExternalsPlugin = require("./ExternalsPlugin");
80 new ExternalsPlugin(options.externalsType, options.externals).apply(
81 compiler
82 );
83 }
84
85 if (options.externalsPresets.node) {
86 const NodeTargetPlugin = require("./node/NodeTargetPlugin");
87 new NodeTargetPlugin().apply(compiler);
88 }
89 if (options.externalsPresets.electronMain) {
90 //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
91 const ElectronTargetPlugin = require("./electron/ElectronTargetPlugin");
92 new ElectronTargetPlugin("main").apply(compiler);
93 }
94 if (options.externalsPresets.electronPreload) {
95 //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
96 const ElectronTargetPlugin = require("./electron/ElectronTargetPlugin");
97 new ElectronTargetPlugin("preload").apply(compiler);
98 }
99 if (options.externalsPresets.electronRenderer) {
100 //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
101 const ElectronTargetPlugin = require("./electron/ElectronTargetPlugin");
102 new ElectronTargetPlugin("renderer").apply(compiler);
103 }
104 if (
105 options.externalsPresets.electron &&
106 !options.externalsPresets.electronMain &&
107 !options.externalsPresets.electronPreload &&
108 !options.externalsPresets.electronRenderer
109 ) {
110 //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
111 const ElectronTargetPlugin = require("./electron/ElectronTargetPlugin");
112 new ElectronTargetPlugin().apply(compiler);
113 }
114 if (options.externalsPresets.nwjs) {
115 //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
116 const ExternalsPlugin = require("./ExternalsPlugin");
117 new ExternalsPlugin("node-commonjs", "nw.gui").apply(compiler);
118 }
119 if (options.externalsPresets.webAsync) {
120 //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
121 const ExternalsPlugin = require("./ExternalsPlugin");
122 new ExternalsPlugin(
123 "import",
124 options.experiments.css
125 ? ({ request, dependencyType }, callback) => {
126 if (dependencyType === "url") {
127 if (/^(\/\/|https?:\/\/)/.test(request))
128 return callback(null, `asset ${request}`);
129 } else if (dependencyType === "css-import") {
130 if (/^(\/\/|https?:\/\/)/.test(request))
131 return callback(null, `css-import ${request}`);
132 } else if (/^(\/\/|https?:\/\/|std:)/.test(request)) {
133 if (/^\.css(\?|$)/.test(request))
134 return callback(null, `css-import ${request}`);
135 return callback(null, `import ${request}`);
136 }
137 callback();
138 }
139 : /^(\/\/|https?:\/\/|std:)/
140 ).apply(compiler);
141 } else if (options.externalsPresets.web) {
142 //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
143 const ExternalsPlugin = require("./ExternalsPlugin");
144 new ExternalsPlugin(
145 "module",
146 options.experiments.css
147 ? ({ request, dependencyType }, callback) => {
148 if (dependencyType === "url") {
149 if (/^(\/\/|https?:\/\/)/.test(request))
150 return callback(null, `asset ${request}`);
151 } else if (dependencyType === "css-import") {
152 if (/^(\/\/|https?:\/\/)/.test(request))
153 return callback(null, `css-import ${request}`);
154 } else if (/^(\/\/|https?:\/\/|std:)/.test(request)) {
155 if (/^\.css(\?|$)/.test(request))
156 return callback(null, `css-import ${request}`);
157 return callback(null, `module ${request}`);
158 }
159 callback();
160 }
161 : /^(\/\/|https?:\/\/|std:)/
162 ).apply(compiler);
163 }
164
165 new ChunkPrefetchPreloadPlugin().apply(compiler);
166
167 if (typeof options.output.chunkFormat === "string") {
168 switch (options.output.chunkFormat) {
169 case "array-push": {
170 const ArrayPushCallbackChunkFormatPlugin = require("./javascript/ArrayPushCallbackChunkFormatPlugin");
171 new ArrayPushCallbackChunkFormatPlugin().apply(compiler);
172 break;
173 }
174 case "commonjs": {
175 const CommonJsChunkFormatPlugin = require("./javascript/CommonJsChunkFormatPlugin");
176 new CommonJsChunkFormatPlugin().apply(compiler);
177 break;
178 }
179 case "module": {
180 const ModuleChunkFormatPlugin = require("./esm/ModuleChunkFormatPlugin");
181 new ModuleChunkFormatPlugin().apply(compiler);
182 break;
183 }
184 default:
185 throw new Error(
186 "Unsupported chunk format '" + options.output.chunkFormat + "'."
187 );
188 }
189 }
190
191 if (options.output.enabledChunkLoadingTypes.length > 0) {
192 for (const type of options.output.enabledChunkLoadingTypes) {
193 const EnableChunkLoadingPlugin = require("./javascript/EnableChunkLoadingPlugin");
194 new EnableChunkLoadingPlugin(type).apply(compiler);
195 }
196 }
197
198 if (options.output.enabledWasmLoadingTypes.length > 0) {
199 for (const type of options.output.enabledWasmLoadingTypes) {
200 const EnableWasmLoadingPlugin = require("./wasm/EnableWasmLoadingPlugin");
201 new EnableWasmLoadingPlugin(type).apply(compiler);
202 }
203 }
204
205 if (options.output.enabledLibraryTypes.length > 0) {
206 for (const type of options.output.enabledLibraryTypes) {
207 const EnableLibraryPlugin = require("./library/EnableLibraryPlugin");
208 new EnableLibraryPlugin(type).apply(compiler);
209 }
210 }
211
212 if (options.output.pathinfo) {
213 const ModuleInfoHeaderPlugin = require("./ModuleInfoHeaderPlugin");
214 new ModuleInfoHeaderPlugin(options.output.pathinfo !== true).apply(
215 compiler
216 );
217 }
218
219 if (options.output.clean) {
220 const CleanPlugin = require("./CleanPlugin");
221 new CleanPlugin(
222 options.output.clean === true ? {} : options.output.clean
223 ).apply(compiler);
224 }
225
226 if (options.devtool) {
227 if (options.devtool.includes("source-map")) {
228 const hidden = options.devtool.includes("hidden");
229 const inline = options.devtool.includes("inline");
230 const evalWrapped = options.devtool.includes("eval");
231 const cheap = options.devtool.includes("cheap");
232 const moduleMaps = options.devtool.includes("module");
233 const noSources = options.devtool.includes("nosources");
234 const Plugin = evalWrapped
235 ? require("./EvalSourceMapDevToolPlugin")
236 : require("./SourceMapDevToolPlugin");
237 new Plugin({
238 filename: inline ? null : options.output.sourceMapFilename,
239 moduleFilenameTemplate: options.output.devtoolModuleFilenameTemplate,
240 fallbackModuleFilenameTemplate:
241 options.output.devtoolFallbackModuleFilenameTemplate,
242 append: hidden ? false : undefined,
243 module: moduleMaps ? true : cheap ? false : true,
244 columns: cheap ? false : true,
245 noSources: noSources,
246 namespace: options.output.devtoolNamespace
247 }).apply(compiler);
248 } else if (options.devtool.includes("eval")) {
249 const EvalDevToolModulePlugin = require("./EvalDevToolModulePlugin");
250 new EvalDevToolModulePlugin({
251 moduleFilenameTemplate: options.output.devtoolModuleFilenameTemplate,
252 namespace: options.output.devtoolNamespace
253 }).apply(compiler);
254 }
255 }
256
257 new JavascriptModulesPlugin().apply(compiler);
258 new JsonModulesPlugin().apply(compiler);
259 new AssetModulesPlugin().apply(compiler);
260
261 if (!options.experiments.outputModule) {
262 if (options.output.module) {
263 throw new Error(
264 "'output.module: true' is only allowed when 'experiments.outputModule' is enabled"
265 );
266 }
267 if (options.output.enabledLibraryTypes.includes("module")) {
268 throw new Error(
269 "library type \"module\" is only allowed when 'experiments.outputModule' is enabled"
270 );
271 }
272 if (options.externalsType === "module") {
273 throw new Error(
274 "'externalsType: \"module\"' is only allowed when 'experiments.outputModule' is enabled"
275 );
276 }
277 }
278
279 if (options.experiments.syncWebAssembly) {
280 const WebAssemblyModulesPlugin = require("./wasm-sync/WebAssemblyModulesPlugin");
281 new WebAssemblyModulesPlugin({
282 mangleImports: options.optimization.mangleWasmImports
283 }).apply(compiler);
284 }
285
286 if (options.experiments.asyncWebAssembly) {
287 const AsyncWebAssemblyModulesPlugin = require("./wasm-async/AsyncWebAssemblyModulesPlugin");
288 new AsyncWebAssemblyModulesPlugin({
289 mangleImports: options.optimization.mangleWasmImports
290 }).apply(compiler);
291 }
292
293 if (options.experiments.css) {
294 const CssModulesPlugin = require("./css/CssModulesPlugin");
295 new CssModulesPlugin(options.experiments.css).apply(compiler);
296 }
297
298 if (options.experiments.lazyCompilation) {
299 const LazyCompilationPlugin = require("./hmr/LazyCompilationPlugin");
300 const lazyOptions =
301 typeof options.experiments.lazyCompilation === "object"
302 ? options.experiments.lazyCompilation
303 : null;
304 new LazyCompilationPlugin({
305 backend:
306 typeof lazyOptions.backend === "function"
307 ? lazyOptions.backend
308 : require("./hmr/lazyCompilationBackend")({
309 ...lazyOptions.backend,
310 client:
311 (lazyOptions.backend && lazyOptions.backend.client) ||
312 require.resolve(
313 `../hot/lazy-compilation-${
314 options.externalsPresets.node ? "node" : "web"
315 }.js`
316 )
317 }),
318 entries: !lazyOptions || lazyOptions.entries !== false,
319 imports: !lazyOptions || lazyOptions.imports !== false,
320 test: (lazyOptions && lazyOptions.test) || undefined
321 }).apply(compiler);
322 }
323
324 if (options.experiments.buildHttp) {
325 const HttpUriPlugin = require("./schemes/HttpUriPlugin");
326 const httpOptions = options.experiments.buildHttp;
327 new HttpUriPlugin(httpOptions).apply(compiler);
328 }
329
330 new EntryOptionPlugin().apply(compiler);
331 compiler.hooks.entryOption.call(options.context, options.entry);
332
333 new RuntimePlugin().apply(compiler);
334
335 new InferAsyncModulesPlugin().apply(compiler);
336
337 new DataUriPlugin().apply(compiler);
338 new FileUriPlugin().apply(compiler);
339
340 new CompatibilityPlugin().apply(compiler);
341 new HarmonyModulesPlugin({
342 topLevelAwait: options.experiments.topLevelAwait
343 }).apply(compiler);
344 if (options.amd !== false) {
345 const AMDPlugin = require("./dependencies/AMDPlugin");
346 const RequireJsStuffPlugin = require("./RequireJsStuffPlugin");
347 new AMDPlugin(options.amd || {}).apply(compiler);
348 new RequireJsStuffPlugin().apply(compiler);
349 }
350 new CommonJsPlugin().apply(compiler);
351 new LoaderPlugin({}).apply(compiler);
352 if (options.node !== false) {
353 const NodeStuffPlugin = require("./NodeStuffPlugin");
354 new NodeStuffPlugin(options.node).apply(compiler);
355 }
356 new APIPlugin().apply(compiler);
357 new ExportsInfoApiPlugin().apply(compiler);
358 new WebpackIsIncludedPlugin().apply(compiler);
359 new ConstPlugin().apply(compiler);
360 new UseStrictPlugin().apply(compiler);
361 new RequireIncludePlugin().apply(compiler);
362 new RequireEnsurePlugin().apply(compiler);
363 new RequireContextPlugin().apply(compiler);
364 new ImportPlugin().apply(compiler);
365 new ImportMetaContextPlugin().apply(compiler);
366 new SystemPlugin().apply(compiler);
367 new ImportMetaPlugin().apply(compiler);
368 new URLPlugin().apply(compiler);
369 new WorkerPlugin(
370 options.output.workerChunkLoading,
371 options.output.workerWasmLoading,
372 options.output.module
373 ).apply(compiler);
374
375 new DefaultStatsFactoryPlugin().apply(compiler);
376 new DefaultStatsPresetPlugin().apply(compiler);
377 new DefaultStatsPrinterPlugin().apply(compiler);
378
379 new JavascriptMetaInfoPlugin().apply(compiler);
380
381 if (typeof options.mode !== "string") {
382 const WarnNoModeSetPlugin = require("./WarnNoModeSetPlugin");
383 new WarnNoModeSetPlugin().apply(compiler);
384 }
385
386 const EnsureChunkConditionsPlugin = require("./optimize/EnsureChunkConditionsPlugin");
387 new EnsureChunkConditionsPlugin().apply(compiler);
388 if (options.optimization.removeAvailableModules) {
389 const RemoveParentModulesPlugin = require("./optimize/RemoveParentModulesPlugin");
390 new RemoveParentModulesPlugin().apply(compiler);
391 }
392 if (options.optimization.removeEmptyChunks) {
393 const RemoveEmptyChunksPlugin = require("./optimize/RemoveEmptyChunksPlugin");
394 new RemoveEmptyChunksPlugin().apply(compiler);
395 }
396 if (options.optimization.mergeDuplicateChunks) {
397 const MergeDuplicateChunksPlugin = require("./optimize/MergeDuplicateChunksPlugin");
398 new MergeDuplicateChunksPlugin().apply(compiler);
399 }
400 if (options.optimization.flagIncludedChunks) {
401 const FlagIncludedChunksPlugin = require("./optimize/FlagIncludedChunksPlugin");
402 new FlagIncludedChunksPlugin().apply(compiler);
403 }
404 if (options.optimization.sideEffects) {
405 const SideEffectsFlagPlugin = require("./optimize/SideEffectsFlagPlugin");
406 new SideEffectsFlagPlugin(
407 options.optimization.sideEffects === true
408 ).apply(compiler);
409 }
410 if (options.optimization.providedExports) {
411 const FlagDependencyExportsPlugin = require("./FlagDependencyExportsPlugin");
412 new FlagDependencyExportsPlugin().apply(compiler);
413 }
414 if (options.optimization.usedExports) {
415 const FlagDependencyUsagePlugin = require("./FlagDependencyUsagePlugin");
416 new FlagDependencyUsagePlugin(
417 options.optimization.usedExports === "global"
418 ).apply(compiler);
419 }
420 if (options.optimization.innerGraph) {
421 const InnerGraphPlugin = require("./optimize/InnerGraphPlugin");
422 new InnerGraphPlugin().apply(compiler);
423 }
424 if (options.optimization.mangleExports) {
425 const MangleExportsPlugin = require("./optimize/MangleExportsPlugin");
426 new MangleExportsPlugin(
427 options.optimization.mangleExports !== "size"
428 ).apply(compiler);
429 }
430 if (options.optimization.concatenateModules) {
431 const ModuleConcatenationPlugin = require("./optimize/ModuleConcatenationPlugin");
432 new ModuleConcatenationPlugin().apply(compiler);
433 }
434 if (options.optimization.splitChunks) {
435 const SplitChunksPlugin = require("./optimize/SplitChunksPlugin");
436 new SplitChunksPlugin(options.optimization.splitChunks).apply(compiler);
437 }
438 if (options.optimization.runtimeChunk) {
439 const RuntimeChunkPlugin = require("./optimize/RuntimeChunkPlugin");
440 new RuntimeChunkPlugin(options.optimization.runtimeChunk).apply(compiler);
441 }
442 if (!options.optimization.emitOnErrors) {
443 const NoEmitOnErrorsPlugin = require("./NoEmitOnErrorsPlugin");
444 new NoEmitOnErrorsPlugin().apply(compiler);
445 }
446 if (options.optimization.realContentHash) {
447 const RealContentHashPlugin = require("./optimize/RealContentHashPlugin");
448 new RealContentHashPlugin({
449 hashFunction: options.output.hashFunction,
450 hashDigest: options.output.hashDigest
451 }).apply(compiler);
452 }
453 if (options.optimization.checkWasmTypes) {
454 const WasmFinalizeExportsPlugin = require("./wasm-sync/WasmFinalizeExportsPlugin");
455 new WasmFinalizeExportsPlugin().apply(compiler);
456 }
457 const moduleIds = options.optimization.moduleIds;
458 if (moduleIds) {
459 switch (moduleIds) {
460 case "natural": {
461 const NaturalModuleIdsPlugin = require("./ids/NaturalModuleIdsPlugin");
462 new NaturalModuleIdsPlugin().apply(compiler);
463 break;
464 }
465 case "named": {
466 const NamedModuleIdsPlugin = require("./ids/NamedModuleIdsPlugin");
467 new NamedModuleIdsPlugin().apply(compiler);
468 break;
469 }
470 case "hashed": {
471 const WarnDeprecatedOptionPlugin = require("./WarnDeprecatedOptionPlugin");
472 const HashedModuleIdsPlugin = require("./ids/HashedModuleIdsPlugin");
473 new WarnDeprecatedOptionPlugin(
474 "optimization.moduleIds",
475 "hashed",
476 "deterministic"
477 ).apply(compiler);
478 new HashedModuleIdsPlugin({
479 hashFunction: options.output.hashFunction
480 }).apply(compiler);
481 break;
482 }
483 case "deterministic": {
484 const DeterministicModuleIdsPlugin = require("./ids/DeterministicModuleIdsPlugin");
485 new DeterministicModuleIdsPlugin().apply(compiler);
486 break;
487 }
488 case "size": {
489 const OccurrenceModuleIdsPlugin = require("./ids/OccurrenceModuleIdsPlugin");
490 new OccurrenceModuleIdsPlugin({
491 prioritiseInitial: true
492 }).apply(compiler);
493 break;
494 }
495 default:
496 throw new Error(
497 `webpack bug: moduleIds: ${moduleIds} is not implemented`
498 );
499 }
500 }
501 const chunkIds = options.optimization.chunkIds;
502 if (chunkIds) {
503 switch (chunkIds) {
504 case "natural": {
505 const NaturalChunkIdsPlugin = require("./ids/NaturalChunkIdsPlugin");
506 new NaturalChunkIdsPlugin().apply(compiler);
507 break;
508 }
509 case "named": {
510 const NamedChunkIdsPlugin = require("./ids/NamedChunkIdsPlugin");
511 new NamedChunkIdsPlugin().apply(compiler);
512 break;
513 }
514 case "deterministic": {
515 const DeterministicChunkIdsPlugin = require("./ids/DeterministicChunkIdsPlugin");
516 new DeterministicChunkIdsPlugin().apply(compiler);
517 break;
518 }
519 case "size": {
520 //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
521 const OccurrenceChunkIdsPlugin = require("./ids/OccurrenceChunkIdsPlugin");
522 new OccurrenceChunkIdsPlugin({
523 prioritiseInitial: true
524 }).apply(compiler);
525 break;
526 }
527 case "total-size": {
528 //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
529 const OccurrenceChunkIdsPlugin = require("./ids/OccurrenceChunkIdsPlugin");
530 new OccurrenceChunkIdsPlugin({
531 prioritiseInitial: false
532 }).apply(compiler);
533 break;
534 }
535 default:
536 throw new Error(
537 `webpack bug: chunkIds: ${chunkIds} is not implemented`
538 );
539 }
540 }
541 if (options.optimization.nodeEnv) {
542 const DefinePlugin = require("./DefinePlugin");
543 new DefinePlugin({
544 "process.env.NODE_ENV": JSON.stringify(options.optimization.nodeEnv)
545 }).apply(compiler);
546 }
547 if (options.optimization.minimize) {
548 for (const minimizer of options.optimization.minimizer) {
549 if (typeof minimizer === "function") {
550 minimizer.call(compiler, compiler);
551 } else if (minimizer !== "...") {
552 minimizer.apply(compiler);
553 }
554 }
555 }
556
557 if (options.performance) {
558 const SizeLimitsPlugin = require("./performance/SizeLimitsPlugin");
559 new SizeLimitsPlugin(options.performance).apply(compiler);
560 }
561
562 new TemplatedPathPlugin().apply(compiler);
563
564 new RecordIdsPlugin({
565 portableIds: options.optimization.portableRecords
566 }).apply(compiler);
567
568 new WarnCaseSensitiveModulesPlugin().apply(compiler);
569
570 const AddManagedPathsPlugin = require("./cache/AddManagedPathsPlugin");
571 new AddManagedPathsPlugin(
572 options.snapshot.managedPaths,
573 options.snapshot.immutablePaths
574 ).apply(compiler);
575
576 if (options.cache && typeof options.cache === "object") {
577 const cacheOptions = options.cache;
578 switch (cacheOptions.type) {
579 case "memory": {
580 if (isFinite(cacheOptions.maxGenerations)) {
581 //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
582 const MemoryWithGcCachePlugin = require("./cache/MemoryWithGcCachePlugin");
583 new MemoryWithGcCachePlugin({
584 maxGenerations: cacheOptions.maxGenerations
585 }).apply(compiler);
586 } else {
587 //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
588 const MemoryCachePlugin = require("./cache/MemoryCachePlugin");
589 new MemoryCachePlugin().apply(compiler);
590 }
591 if (cacheOptions.cacheUnaffected) {
592 if (!options.experiments.cacheUnaffected) {
593 throw new Error(
594 "'cache.cacheUnaffected: true' is only allowed when 'experiments.cacheUnaffected' is enabled"
595 );
596 }
597 compiler.moduleMemCaches = new Map();
598 }
599 break;
600 }
601 case "filesystem": {
602 const AddBuildDependenciesPlugin = require("./cache/AddBuildDependenciesPlugin");
603 for (const key in cacheOptions.buildDependencies) {
604 const list = cacheOptions.buildDependencies[key];
605 new AddBuildDependenciesPlugin(list).apply(compiler);
606 }
607 if (!isFinite(cacheOptions.maxMemoryGenerations)) {
608 //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
609 const MemoryCachePlugin = require("./cache/MemoryCachePlugin");
610 new MemoryCachePlugin().apply(compiler);
611 } else if (cacheOptions.maxMemoryGenerations !== 0) {
612 //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
613 const MemoryWithGcCachePlugin = require("./cache/MemoryWithGcCachePlugin");
614 new MemoryWithGcCachePlugin({
615 maxGenerations: cacheOptions.maxMemoryGenerations
616 }).apply(compiler);
617 }
618 if (cacheOptions.memoryCacheUnaffected) {
619 if (!options.experiments.cacheUnaffected) {
620 throw new Error(
621 "'cache.memoryCacheUnaffected: true' is only allowed when 'experiments.cacheUnaffected' is enabled"
622 );
623 }
624 compiler.moduleMemCaches = new Map();
625 }
626 switch (cacheOptions.store) {
627 case "pack": {
628 const IdleFileCachePlugin = require("./cache/IdleFileCachePlugin");
629 const PackFileCacheStrategy = require("./cache/PackFileCacheStrategy");
630 new IdleFileCachePlugin(
631 new PackFileCacheStrategy({
632 compiler,
633 fs: compiler.intermediateFileSystem,
634 context: options.context,
635 cacheLocation: cacheOptions.cacheLocation,
636 version: cacheOptions.version,
637 logger: compiler.getInfrastructureLogger(
638 "webpack.cache.PackFileCacheStrategy"
639 ),
640 snapshot: options.snapshot,
641 maxAge: cacheOptions.maxAge,
642 profile: cacheOptions.profile,
643 allowCollectingMemory: cacheOptions.allowCollectingMemory,
644 compression: cacheOptions.compression
645 }),
646 cacheOptions.idleTimeout,
647 cacheOptions.idleTimeoutForInitialStore,
648 cacheOptions.idleTimeoutAfterLargeChanges
649 ).apply(compiler);
650 break;
651 }
652 default:
653 throw new Error("Unhandled value for cache.store");
654 }
655 break;
656 }
657 default:
658 // @ts-expect-error Property 'type' does not exist on type 'never'. ts(2339)
659 throw new Error(`Unknown cache type ${cacheOptions.type}`);
660 }
661 }
662 new ResolverCachePlugin().apply(compiler);
663
664 if (options.ignoreWarnings && options.ignoreWarnings.length > 0) {
665 const IgnoreWarningsPlugin = require("./IgnoreWarningsPlugin");
666 new IgnoreWarningsPlugin(options.ignoreWarnings).apply(compiler);
667 }
668
669 compiler.hooks.afterPlugins.call(compiler);
670 if (!compiler.inputFileSystem) {
671 throw new Error("No input filesystem provided");
672 }
673 compiler.resolverFactory.hooks.resolveOptions
674 .for("normal")
675 .tap("WebpackOptionsApply", resolveOptions => {
676 resolveOptions = cleverMerge(options.resolve, resolveOptions);
677 resolveOptions.fileSystem = compiler.inputFileSystem;
678 return resolveOptions;
679 });
680 compiler.resolverFactory.hooks.resolveOptions
681 .for("context")
682 .tap("WebpackOptionsApply", resolveOptions => {
683 resolveOptions = cleverMerge(options.resolve, resolveOptions);
684 resolveOptions.fileSystem = compiler.inputFileSystem;
685 resolveOptions.resolveToContext = true;
686 return resolveOptions;
687 });
688 compiler.resolverFactory.hooks.resolveOptions
689 .for("loader")
690 .tap("WebpackOptionsApply", resolveOptions => {
691 resolveOptions = cleverMerge(options.resolveLoader, resolveOptions);
692 resolveOptions.fileSystem = compiler.inputFileSystem;
693 return resolveOptions;
694 });
695 compiler.hooks.afterResolvers.call(compiler);
696 return options;
697 }
698}
699
700module.exports = WebpackOptionsApply;