source: imaps-frontend/node_modules/webpack/lib/config/defaults.js

main
Last change on this file was 79a0317, checked in by stefan toskovski <stefantoska84@…>, 3 days ago

F4 Finalna Verzija

  • Property mode set to 100644
File size: 48.1 KB
Line 
1/*
2 MIT License http://www.opensource.org/licenses/mit-license.php
3 Author Tobias Koppers @sokra
4*/
5
6"use strict";
7
8const fs = require("fs");
9const path = require("path");
10const {
11 JAVASCRIPT_MODULE_TYPE_AUTO,
12 JAVASCRIPT_MODULE_TYPE_ESM,
13 JAVASCRIPT_MODULE_TYPE_DYNAMIC,
14 JSON_MODULE_TYPE,
15 WEBASSEMBLY_MODULE_TYPE_ASYNC,
16 WEBASSEMBLY_MODULE_TYPE_SYNC,
17 ASSET_MODULE_TYPE,
18 ASSET_MODULE_TYPE_INLINE,
19 ASSET_MODULE_TYPE_RESOURCE,
20 CSS_MODULE_TYPE_AUTO,
21 CSS_MODULE_TYPE,
22 CSS_MODULE_TYPE_MODULE,
23 CSS_MODULE_TYPE_GLOBAL
24} = require("../ModuleTypeConstants");
25const Template = require("../Template");
26const { cleverMerge } = require("../util/cleverMerge");
27const {
28 getTargetsProperties,
29 getTargetProperties,
30 getDefaultTarget
31} = require("./target");
32
33/** @typedef {import("../../declarations/WebpackOptions").CacheOptions} CacheOptions */
34/** @typedef {import("../../declarations/WebpackOptions").CacheOptionsNormalized} CacheOptionsNormalized */
35/** @typedef {import("../../declarations/WebpackOptions").Context} Context */
36/** @typedef {import("../../declarations/WebpackOptions").CssGeneratorOptions} CssGeneratorOptions */
37/** @typedef {import("../../declarations/WebpackOptions").CssParserOptions} CssParserOptions */
38/** @typedef {import("../../declarations/WebpackOptions").EntryDescription} EntryDescription */
39/** @typedef {import("../../declarations/WebpackOptions").EntryNormalized} Entry */
40/** @typedef {import("../../declarations/WebpackOptions").EntryStaticNormalized} EntryStaticNormalized */
41/** @typedef {import("../../declarations/WebpackOptions").Environment} Environment */
42/** @typedef {import("../../declarations/WebpackOptions").Experiments} Experiments */
43/** @typedef {import("../../declarations/WebpackOptions").ExperimentsNormalized} ExperimentsNormalized */
44/** @typedef {import("../../declarations/WebpackOptions").ExternalsPresets} ExternalsPresets */
45/** @typedef {import("../../declarations/WebpackOptions").ExternalsType} ExternalsType */
46/** @typedef {import("../../declarations/WebpackOptions").FileCacheOptions} FileCacheOptions */
47/** @typedef {import("../../declarations/WebpackOptions").GeneratorOptionsByModuleTypeKnown} GeneratorOptionsByModuleTypeKnown */
48/** @typedef {import("../../declarations/WebpackOptions").InfrastructureLogging} InfrastructureLogging */
49/** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */
50/** @typedef {import("../../declarations/WebpackOptions").Library} Library */
51/** @typedef {import("../../declarations/WebpackOptions").LibraryName} LibraryName */
52/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */
53/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */
54/** @typedef {import("../../declarations/WebpackOptions").Loader} Loader */
55/** @typedef {import("../../declarations/WebpackOptions").Mode} Mode */
56/** @typedef {import("../../declarations/WebpackOptions").ModuleOptionsNormalized} ModuleOptions */
57/** @typedef {import("../../declarations/WebpackOptions").Node} WebpackNode */
58/** @typedef {import("../../declarations/WebpackOptions").Optimization} Optimization */
59/** @typedef {import("../../declarations/WebpackOptions").OptimizationSplitChunksOptions} OptimizationSplitChunksOptions */
60/** @typedef {import("../../declarations/WebpackOptions").OutputNormalized} Output */
61/** @typedef {import("../../declarations/WebpackOptions").ParserOptionsByModuleTypeKnown} ParserOptionsByModuleTypeKnown */
62/** @typedef {import("../../declarations/WebpackOptions").Performance} Performance */
63/** @typedef {import("../../declarations/WebpackOptions").ResolveOptions} ResolveOptions */
64/** @typedef {import("../../declarations/WebpackOptions").RuleSetRules} RuleSetRules */
65/** @typedef {import("../../declarations/WebpackOptions").SnapshotOptions} SnapshotOptions */
66/** @typedef {import("../../declarations/WebpackOptions").Target} Target */
67/** @typedef {import("../../declarations/WebpackOptions").WebpackOptions} WebpackOptions */
68/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptionsNormalized */
69/** @typedef {import("../Compiler")} Compiler */
70/** @typedef {import("../Module")} Module */
71/** @typedef {import("./target").PlatformTargetProperties} PlatformTargetProperties */
72/** @typedef {import("./target").TargetProperties} TargetProperties */
73
74/**
75 * @typedef {object} ResolvedOptions
76 * @property {PlatformTargetProperties | false} platform - platform target properties
77 */
78
79const NODE_MODULES_REGEXP = /[\\/]node_modules[\\/]/i;
80const DEFAULT_CACHE_NAME = "default";
81
82/**
83 * Sets a constant default value when undefined
84 * @template T
85 * @template {keyof T} P
86 * @param {T} obj an object
87 * @param {P} prop a property of this object
88 * @param {T[P]} value a default value of the property
89 * @returns {void}
90 */
91const D = (obj, prop, value) => {
92 if (obj[prop] === undefined) {
93 obj[prop] = value;
94 }
95};
96
97/**
98 * Sets a dynamic default value when undefined, by calling the factory function
99 * @template T
100 * @template {keyof T} P
101 * @param {T} obj an object
102 * @param {P} prop a property of this object
103 * @param {function(): T[P]} factory a default value factory for the property
104 * @returns {void}
105 */
106const F = (obj, prop, factory) => {
107 if (obj[prop] === undefined) {
108 obj[prop] = factory();
109 }
110};
111
112/**
113 * Sets a dynamic default value when undefined, by calling the factory function.
114 * factory must return an array or undefined
115 * When the current value is already an array an contains "..." it's replaced with
116 * the result of the factory function
117 * @template T
118 * @template {keyof T} P
119 * @param {T} obj an object
120 * @param {P} prop a property of this object
121 * @param {function(): T[P]} factory a default value factory for the property
122 * @returns {void}
123 */
124const A = (obj, prop, factory) => {
125 const value = obj[prop];
126 if (value === undefined) {
127 obj[prop] = factory();
128 } else if (Array.isArray(value)) {
129 /** @type {EXPECTED_ANY[] | undefined} */
130 let newArray;
131 for (let i = 0; i < value.length; i++) {
132 const item = value[i];
133 if (item === "...") {
134 if (newArray === undefined) {
135 newArray = value.slice(0, i);
136 obj[prop] = /** @type {T[P]} */ (/** @type {unknown} */ (newArray));
137 }
138 const items = /** @type {EXPECTED_ANY[]} */ (
139 /** @type {unknown} */ (factory())
140 );
141 if (items !== undefined) {
142 for (const item of items) {
143 newArray.push(item);
144 }
145 }
146 } else if (newArray !== undefined) {
147 newArray.push(item);
148 }
149 }
150 }
151};
152
153/**
154 * @param {WebpackOptionsNormalized} options options to be modified
155 * @returns {void}
156 */
157const applyWebpackOptionsBaseDefaults = options => {
158 F(options, "context", () => process.cwd());
159 applyInfrastructureLoggingDefaults(options.infrastructureLogging);
160};
161
162/**
163 * @param {WebpackOptionsNormalized} options options to be modified
164 * @param {number} [compilerIndex] index of compiler
165 * @returns {ResolvedOptions} Resolved options after apply defaults
166 */
167const applyWebpackOptionsDefaults = (options, compilerIndex) => {
168 F(options, "context", () => process.cwd());
169 F(options, "target", () =>
170 getDefaultTarget(/** @type {string} */ (options.context))
171 );
172
173 const { mode, name, target } = options;
174
175 const targetProperties =
176 target === false
177 ? /** @type {false} */ (false)
178 : typeof target === "string"
179 ? getTargetProperties(target, /** @type {Context} */ (options.context))
180 : getTargetsProperties(
181 /** @type {string[]} */ (target),
182 /** @type {Context} */ (options.context)
183 );
184
185 const development = mode === "development";
186 const production = mode === "production" || !mode;
187
188 if (typeof options.entry !== "function") {
189 for (const key of Object.keys(options.entry)) {
190 F(
191 options.entry[key],
192 "import",
193 () => /** @type {[string]} */ (["./src"])
194 );
195 }
196 }
197
198 F(options, "devtool", () => (development ? "eval" : false));
199 D(options, "watch", false);
200 D(options, "profile", false);
201 D(options, "parallelism", 100);
202 D(options, "recordsInputPath", false);
203 D(options, "recordsOutputPath", false);
204
205 applyExperimentsDefaults(options.experiments, {
206 production,
207 development,
208 targetProperties
209 });
210
211 const futureDefaults =
212 /** @type {NonNullable<ExperimentsNormalized["futureDefaults"]>} */
213 (options.experiments.futureDefaults);
214
215 F(options, "cache", () =>
216 development ? { type: /** @type {"memory"} */ ("memory") } : false
217 );
218 applyCacheDefaults(options.cache, {
219 name: name || DEFAULT_CACHE_NAME,
220 mode: mode || "production",
221 development,
222 cacheUnaffected: options.experiments.cacheUnaffected,
223 compilerIndex
224 });
225 const cache = Boolean(options.cache);
226
227 applySnapshotDefaults(options.snapshot, {
228 production,
229 futureDefaults
230 });
231
232 applyOutputDefaults(options.output, {
233 context: /** @type {Context} */ (options.context),
234 targetProperties,
235 isAffectedByBrowserslist:
236 target === undefined ||
237 (typeof target === "string" && target.startsWith("browserslist")) ||
238 (Array.isArray(target) &&
239 target.some(target => target.startsWith("browserslist"))),
240 outputModule:
241 /** @type {NonNullable<ExperimentsNormalized["outputModule"]>} */
242 (options.experiments.outputModule),
243 development,
244 entry: options.entry,
245 futureDefaults,
246 asyncWebAssembly:
247 /** @type {NonNullable<ExperimentsNormalized["asyncWebAssembly"]>} */
248 (options.experiments.asyncWebAssembly)
249 });
250
251 applyModuleDefaults(options.module, {
252 cache,
253 syncWebAssembly:
254 /** @type {NonNullable<ExperimentsNormalized["syncWebAssembly"]>} */
255 (options.experiments.syncWebAssembly),
256 asyncWebAssembly:
257 /** @type {NonNullable<ExperimentsNormalized["asyncWebAssembly"]>} */
258 (options.experiments.asyncWebAssembly),
259 css:
260 /** @type {NonNullable<ExperimentsNormalized["css"]>} */
261 (options.experiments.css),
262 futureDefaults,
263 isNode: targetProperties && targetProperties.node === true,
264 uniqueName: options.output.uniqueName,
265 targetProperties
266 });
267
268 applyExternalsPresetsDefaults(options.externalsPresets, {
269 targetProperties,
270 buildHttp: Boolean(options.experiments.buildHttp)
271 });
272
273 applyLoaderDefaults(
274 /** @type {NonNullable<WebpackOptionsNormalized["loader"]>} */ (
275 options.loader
276 ),
277 { targetProperties, environment: options.output.environment }
278 );
279
280 F(options, "externalsType", () => {
281 const validExternalTypes = require("../../schemas/WebpackOptions.json")
282 .definitions.ExternalsType.enum;
283 return options.output.library &&
284 validExternalTypes.includes(options.output.library.type)
285 ? /** @type {ExternalsType} */ (options.output.library.type)
286 : options.output.module
287 ? "module-import"
288 : "var";
289 });
290
291 applyNodeDefaults(options.node, {
292 futureDefaults:
293 /** @type {NonNullable<WebpackOptionsNormalized["experiments"]["futureDefaults"]>} */
294 (options.experiments.futureDefaults),
295 outputModule:
296 /** @type {NonNullable<WebpackOptionsNormalized["output"]["module"]>} */
297 (options.output.module),
298 targetProperties
299 });
300
301 F(options, "performance", () =>
302 production &&
303 targetProperties &&
304 (targetProperties.browser || targetProperties.browser === null)
305 ? {}
306 : false
307 );
308 applyPerformanceDefaults(
309 /** @type {NonNullable<WebpackOptionsNormalized["performance"]>} */
310 (options.performance),
311 {
312 production
313 }
314 );
315
316 applyOptimizationDefaults(options.optimization, {
317 development,
318 production,
319 css:
320 /** @type {NonNullable<ExperimentsNormalized["css"]>} */
321 (options.experiments.css),
322 records: Boolean(options.recordsInputPath || options.recordsOutputPath)
323 });
324
325 options.resolve = cleverMerge(
326 getResolveDefaults({
327 cache,
328 context: /** @type {Context} */ (options.context),
329 targetProperties,
330 mode: /** @type {Mode} */ (options.mode),
331 css:
332 /** @type {NonNullable<ExperimentsNormalized["css"]>} */
333 (options.experiments.css)
334 }),
335 options.resolve
336 );
337
338 options.resolveLoader = cleverMerge(
339 getResolveLoaderDefaults({ cache }),
340 options.resolveLoader
341 );
342
343 return {
344 platform:
345 targetProperties === false
346 ? targetProperties
347 : {
348 web: targetProperties.web,
349 browser: targetProperties.browser,
350 webworker: targetProperties.webworker,
351 node: targetProperties.node,
352 nwjs: targetProperties.nwjs,
353 electron: targetProperties.electron
354 }
355 };
356};
357
358/**
359 * @param {ExperimentsNormalized} experiments options
360 * @param {object} options options
361 * @param {boolean} options.production is production
362 * @param {boolean} options.development is development mode
363 * @param {TargetProperties | false} options.targetProperties target properties
364 * @returns {void}
365 */
366const applyExperimentsDefaults = (
367 experiments,
368 { production, development, targetProperties }
369) => {
370 D(experiments, "futureDefaults", false);
371 D(experiments, "backCompat", !experiments.futureDefaults);
372 D(experiments, "syncWebAssembly", false);
373 D(experiments, "asyncWebAssembly", experiments.futureDefaults);
374 D(experiments, "outputModule", false);
375 D(experiments, "layers", false);
376 D(experiments, "lazyCompilation", undefined);
377 D(experiments, "buildHttp", undefined);
378 D(experiments, "cacheUnaffected", experiments.futureDefaults);
379 F(experiments, "css", () => (experiments.futureDefaults ? true : undefined));
380
381 // TODO webpack 6: remove this. topLevelAwait should be enabled by default
382 let shouldEnableTopLevelAwait = true;
383 if (typeof experiments.topLevelAwait === "boolean") {
384 shouldEnableTopLevelAwait = experiments.topLevelAwait;
385 }
386 D(experiments, "topLevelAwait", shouldEnableTopLevelAwait);
387
388 if (typeof experiments.buildHttp === "object") {
389 D(experiments.buildHttp, "frozen", production);
390 D(experiments.buildHttp, "upgrade", false);
391 }
392};
393
394/**
395 * @param {CacheOptionsNormalized} cache options
396 * @param {object} options options
397 * @param {string} options.name name
398 * @param {Mode} options.mode mode
399 * @param {boolean} options.development is development mode
400 * @param {number} [options.compilerIndex] index of compiler
401 * @param {Experiments["cacheUnaffected"]} options.cacheUnaffected the cacheUnaffected experiment is enabled
402 * @returns {void}
403 */
404const applyCacheDefaults = (
405 cache,
406 { name, mode, development, cacheUnaffected, compilerIndex }
407) => {
408 if (cache === false) return;
409 switch (cache.type) {
410 case "filesystem":
411 F(cache, "name", () =>
412 compilerIndex !== undefined
413 ? `${`${name}-${mode}`}__compiler${compilerIndex + 1}__`
414 : `${name}-${mode}`
415 );
416 D(cache, "version", "");
417 F(cache, "cacheDirectory", () => {
418 const cwd = process.cwd();
419 /** @type {string | undefined} */
420 let dir = cwd;
421 for (;;) {
422 try {
423 if (fs.statSync(path.join(dir, "package.json")).isFile()) break;
424 // eslint-disable-next-line no-empty
425 } catch (_err) {}
426 const parent = path.dirname(dir);
427 if (dir === parent) {
428 dir = undefined;
429 break;
430 }
431 dir = parent;
432 }
433 if (!dir) {
434 return path.resolve(cwd, ".cache/webpack");
435 } else if (process.versions.pnp === "1") {
436 return path.resolve(dir, ".pnp/.cache/webpack");
437 } else if (process.versions.pnp === "3") {
438 return path.resolve(dir, ".yarn/.cache/webpack");
439 }
440 return path.resolve(dir, "node_modules/.cache/webpack");
441 });
442 F(cache, "cacheLocation", () =>
443 path.resolve(
444 /** @type {NonNullable<FileCacheOptions["cacheDirectory"]>} */
445 (cache.cacheDirectory),
446 /** @type {NonNullable<FileCacheOptions["name"]>} */ (cache.name)
447 )
448 );
449 D(cache, "hashAlgorithm", "md4");
450 D(cache, "store", "pack");
451 D(cache, "compression", false);
452 D(cache, "profile", false);
453 D(cache, "idleTimeout", 60000);
454 D(cache, "idleTimeoutForInitialStore", 5000);
455 D(cache, "idleTimeoutAfterLargeChanges", 1000);
456 D(cache, "maxMemoryGenerations", development ? 5 : Infinity);
457 D(cache, "maxAge", 1000 * 60 * 60 * 24 * 60); // 1 month
458 D(cache, "allowCollectingMemory", development);
459 D(cache, "memoryCacheUnaffected", development && cacheUnaffected);
460 D(cache, "readonly", false);
461 D(
462 /** @type {NonNullable<FileCacheOptions["buildDependencies"]>} */
463 (cache.buildDependencies),
464 "defaultWebpack",
465 [path.resolve(__dirname, "..") + path.sep]
466 );
467 break;
468 case "memory":
469 D(cache, "maxGenerations", Infinity);
470 D(cache, "cacheUnaffected", development && cacheUnaffected);
471 break;
472 }
473};
474
475/**
476 * @param {SnapshotOptions} snapshot options
477 * @param {object} options options
478 * @param {boolean} options.production is production
479 * @param {boolean} options.futureDefaults is future defaults enabled
480 * @returns {void}
481 */
482const applySnapshotDefaults = (snapshot, { production, futureDefaults }) => {
483 if (futureDefaults) {
484 F(snapshot, "managedPaths", () =>
485 process.versions.pnp === "3"
486 ? [
487 /^(.+?(?:[\\/]\.yarn[\\/]unplugged[\\/][^\\/]+)?[\\/]node_modules[\\/])/
488 ]
489 : [/^(.+?[\\/]node_modules[\\/])/]
490 );
491 F(snapshot, "immutablePaths", () =>
492 process.versions.pnp === "3"
493 ? [/^(.+?[\\/]cache[\\/][^\\/]+\.zip[\\/]node_modules[\\/])/]
494 : []
495 );
496 } else {
497 A(snapshot, "managedPaths", () => {
498 if (process.versions.pnp === "3") {
499 const match =
500 /^(.+?)[\\/]cache[\\/]watchpack-npm-[^\\/]+\.zip[\\/]node_modules[\\/]/.exec(
501 require.resolve("watchpack")
502 );
503 if (match) {
504 return [path.resolve(match[1], "unplugged")];
505 }
506 } else {
507 const match = /^(.+?[\\/]node_modules[\\/])/.exec(
508 require.resolve("watchpack")
509 );
510 if (match) {
511 return [match[1]];
512 }
513 }
514 return [];
515 });
516 A(snapshot, "immutablePaths", () => {
517 if (process.versions.pnp === "1") {
518 const match =
519 /^(.+?[\\/]v4)[\\/]npm-watchpack-[^\\/]+-[\da-f]{40}[\\/]node_modules[\\/]/.exec(
520 require.resolve("watchpack")
521 );
522 if (match) {
523 return [match[1]];
524 }
525 } else if (process.versions.pnp === "3") {
526 const match =
527 /^(.+?)[\\/]watchpack-npm-[^\\/]+\.zip[\\/]node_modules[\\/]/.exec(
528 require.resolve("watchpack")
529 );
530 if (match) {
531 return [match[1]];
532 }
533 }
534 return [];
535 });
536 }
537 F(snapshot, "unmanagedPaths", () => []);
538 F(snapshot, "resolveBuildDependencies", () => ({
539 timestamp: true,
540 hash: true
541 }));
542 F(snapshot, "buildDependencies", () => ({ timestamp: true, hash: true }));
543 F(snapshot, "module", () =>
544 production ? { timestamp: true, hash: true } : { timestamp: true }
545 );
546 F(snapshot, "resolve", () =>
547 production ? { timestamp: true, hash: true } : { timestamp: true }
548 );
549};
550
551/**
552 * @param {JavascriptParserOptions} parserOptions parser options
553 * @param {object} options options
554 * @param {boolean} options.futureDefaults is future defaults enabled
555 * @param {boolean} options.isNode is node target platform
556 * @returns {void}
557 */
558const applyJavascriptParserOptionsDefaults = (
559 parserOptions,
560 { futureDefaults, isNode }
561) => {
562 D(parserOptions, "unknownContextRequest", ".");
563 D(parserOptions, "unknownContextRegExp", false);
564 D(parserOptions, "unknownContextRecursive", true);
565 D(parserOptions, "unknownContextCritical", true);
566 D(parserOptions, "exprContextRequest", ".");
567 D(parserOptions, "exprContextRegExp", false);
568 D(parserOptions, "exprContextRecursive", true);
569 D(parserOptions, "exprContextCritical", true);
570 D(parserOptions, "wrappedContextRegExp", /.*/);
571 D(parserOptions, "wrappedContextRecursive", true);
572 D(parserOptions, "wrappedContextCritical", false);
573 D(parserOptions, "strictThisContextOnImports", false);
574 D(parserOptions, "importMeta", true);
575 D(parserOptions, "dynamicImportMode", "lazy");
576 D(parserOptions, "dynamicImportPrefetch", false);
577 D(parserOptions, "dynamicImportPreload", false);
578 D(parserOptions, "dynamicImportFetchPriority", false);
579 D(parserOptions, "createRequire", isNode);
580 if (futureDefaults) D(parserOptions, "exportsPresence", "error");
581};
582
583/**
584 * @param {CssGeneratorOptions} generatorOptions generator options
585 * @param {object} options options
586 * @param {TargetProperties | false} options.targetProperties target properties
587 * @returns {void}
588 */
589const applyCssGeneratorOptionsDefaults = (
590 generatorOptions,
591 { targetProperties }
592) => {
593 D(
594 generatorOptions,
595 "exportsOnly",
596 !targetProperties || targetProperties.document === false
597 );
598 D(generatorOptions, "esModule", true);
599};
600
601/**
602 * @param {ModuleOptions} module options
603 * @param {object} options options
604 * @param {boolean} options.cache is caching enabled
605 * @param {boolean} options.syncWebAssembly is syncWebAssembly enabled
606 * @param {boolean} options.asyncWebAssembly is asyncWebAssembly enabled
607 * @param {boolean} options.css is css enabled
608 * @param {boolean} options.futureDefaults is future defaults enabled
609 * @param {string} options.uniqueName the unique name
610 * @param {boolean} options.isNode is node target platform
611 * @param {TargetProperties | false} options.targetProperties target properties
612 * @returns {void}
613 */
614const applyModuleDefaults = (
615 module,
616 {
617 cache,
618 syncWebAssembly,
619 asyncWebAssembly,
620 css,
621 futureDefaults,
622 isNode,
623 uniqueName,
624 targetProperties
625 }
626) => {
627 if (cache) {
628 D(
629 module,
630 "unsafeCache",
631 /**
632 * @param {Module} module module
633 * @returns {boolean | null | string} true, if we want to cache the module
634 */
635 module => {
636 const name = module.nameForCondition();
637 return name && NODE_MODULES_REGEXP.test(name);
638 }
639 );
640 } else {
641 D(module, "unsafeCache", false);
642 }
643
644 F(module.parser, ASSET_MODULE_TYPE, () => ({}));
645 F(
646 /** @type {NonNullable<ParserOptionsByModuleTypeKnown["asset"]>} */
647 (module.parser[ASSET_MODULE_TYPE]),
648 "dataUrlCondition",
649 () => ({})
650 );
651 if (
652 typeof (
653 /** @type {NonNullable<ParserOptionsByModuleTypeKnown["asset"]>} */
654 (module.parser[ASSET_MODULE_TYPE]).dataUrlCondition
655 ) === "object"
656 ) {
657 D(
658 /** @type {NonNullable<ParserOptionsByModuleTypeKnown["asset"]>} */
659 (module.parser[ASSET_MODULE_TYPE]).dataUrlCondition,
660 "maxSize",
661 8096
662 );
663 }
664
665 F(module.parser, "javascript", () => ({}));
666
667 applyJavascriptParserOptionsDefaults(
668 /** @type {NonNullable<ParserOptionsByModuleTypeKnown["javascript"]>} */
669 (module.parser.javascript),
670 {
671 futureDefaults,
672 isNode
673 }
674 );
675
676 if (css) {
677 F(module.parser, CSS_MODULE_TYPE, () => ({}));
678
679 D(module.parser[CSS_MODULE_TYPE], "import", true);
680 D(module.parser[CSS_MODULE_TYPE], "url", true);
681 D(module.parser[CSS_MODULE_TYPE], "namedExports", true);
682
683 F(module.generator, CSS_MODULE_TYPE, () => ({}));
684
685 applyCssGeneratorOptionsDefaults(
686 /** @type {NonNullable<GeneratorOptionsByModuleTypeKnown["css"]>} */
687 (module.generator[CSS_MODULE_TYPE]),
688 { targetProperties }
689 );
690
691 const localIdentName =
692 uniqueName.length > 0 ? "[uniqueName]-[id]-[local]" : "[id]-[local]";
693
694 F(module.generator, CSS_MODULE_TYPE_AUTO, () => ({}));
695 D(module.generator[CSS_MODULE_TYPE_AUTO], "localIdentName", localIdentName);
696 D(module.generator[CSS_MODULE_TYPE_AUTO], "exportsConvention", "as-is");
697
698 F(module.generator, CSS_MODULE_TYPE_MODULE, () => ({}));
699 D(
700 module.generator[CSS_MODULE_TYPE_MODULE],
701 "localIdentName",
702 localIdentName
703 );
704 D(module.generator[CSS_MODULE_TYPE_MODULE], "exportsConvention", "as-is");
705
706 F(module.generator, CSS_MODULE_TYPE_GLOBAL, () => ({}));
707 D(
708 module.generator[CSS_MODULE_TYPE_GLOBAL],
709 "localIdentName",
710 localIdentName
711 );
712 D(module.generator[CSS_MODULE_TYPE_GLOBAL], "exportsConvention", "as-is");
713 }
714
715 A(module, "defaultRules", () => {
716 const esm = {
717 type: JAVASCRIPT_MODULE_TYPE_ESM,
718 resolve: {
719 byDependency: {
720 esm: {
721 fullySpecified: true
722 }
723 }
724 }
725 };
726 const commonjs = {
727 type: JAVASCRIPT_MODULE_TYPE_DYNAMIC
728 };
729 /** @type {RuleSetRules} */
730 const rules = [
731 {
732 mimetype: "application/node",
733 type: JAVASCRIPT_MODULE_TYPE_AUTO
734 },
735 {
736 test: /\.json$/i,
737 type: JSON_MODULE_TYPE
738 },
739 {
740 mimetype: "application/json",
741 type: JSON_MODULE_TYPE
742 },
743 {
744 test: /\.mjs$/i,
745 ...esm
746 },
747 {
748 test: /\.js$/i,
749 descriptionData: {
750 type: "module"
751 },
752 ...esm
753 },
754 {
755 test: /\.cjs$/i,
756 ...commonjs
757 },
758 {
759 test: /\.js$/i,
760 descriptionData: {
761 type: "commonjs"
762 },
763 ...commonjs
764 },
765 {
766 mimetype: {
767 or: ["text/javascript", "application/javascript"]
768 },
769 ...esm
770 }
771 ];
772 if (asyncWebAssembly) {
773 const wasm = {
774 type: WEBASSEMBLY_MODULE_TYPE_ASYNC,
775 rules: [
776 {
777 descriptionData: {
778 type: "module"
779 },
780 resolve: {
781 fullySpecified: true
782 }
783 }
784 ]
785 };
786 rules.push({
787 test: /\.wasm$/i,
788 ...wasm
789 });
790 rules.push({
791 mimetype: "application/wasm",
792 ...wasm
793 });
794 } else if (syncWebAssembly) {
795 const wasm = {
796 type: WEBASSEMBLY_MODULE_TYPE_SYNC,
797 rules: [
798 {
799 descriptionData: {
800 type: "module"
801 },
802 resolve: {
803 fullySpecified: true
804 }
805 }
806 ]
807 };
808 rules.push({
809 test: /\.wasm$/i,
810 ...wasm
811 });
812 rules.push({
813 mimetype: "application/wasm",
814 ...wasm
815 });
816 }
817 if (css) {
818 const resolve = {
819 fullySpecified: true,
820 preferRelative: true
821 };
822 rules.push({
823 test: /\.css$/i,
824 type: CSS_MODULE_TYPE_AUTO,
825 resolve
826 });
827 rules.push({
828 mimetype: "text/css+module",
829 type: CSS_MODULE_TYPE_MODULE,
830 resolve
831 });
832 rules.push({
833 mimetype: "text/css",
834 type: CSS_MODULE_TYPE,
835 resolve
836 });
837 }
838 rules.push(
839 {
840 dependency: "url",
841 oneOf: [
842 {
843 scheme: /^data$/,
844 type: ASSET_MODULE_TYPE_INLINE
845 },
846 {
847 type: ASSET_MODULE_TYPE_RESOURCE
848 }
849 ]
850 },
851 {
852 assert: { type: JSON_MODULE_TYPE },
853 type: JSON_MODULE_TYPE
854 },
855 {
856 with: { type: JSON_MODULE_TYPE },
857 type: JSON_MODULE_TYPE
858 }
859 );
860 return rules;
861 });
862};
863
864/**
865 * @param {Output} output options
866 * @param {object} options options
867 * @param {string} options.context context
868 * @param {TargetProperties | false} options.targetProperties target properties
869 * @param {boolean} options.isAffectedByBrowserslist is affected by browserslist
870 * @param {boolean} options.outputModule is outputModule experiment enabled
871 * @param {boolean} options.development is development mode
872 * @param {Entry} options.entry entry option
873 * @param {boolean} options.futureDefaults is future defaults enabled
874 * @param {boolean} options.asyncWebAssembly is asyncWebAssembly enabled
875 * @returns {void}
876 */
877const applyOutputDefaults = (
878 output,
879 {
880 context,
881 targetProperties: tp,
882 isAffectedByBrowserslist,
883 outputModule,
884 development,
885 entry,
886 futureDefaults,
887 asyncWebAssembly
888 }
889) => {
890 /**
891 * @param {Library=} library the library option
892 * @returns {string} a readable library name
893 */
894 const getLibraryName = library => {
895 const libraryName =
896 typeof library === "object" &&
897 library &&
898 !Array.isArray(library) &&
899 "type" in library
900 ? library.name
901 : /** @type {LibraryName} */ (library);
902 if (Array.isArray(libraryName)) {
903 return libraryName.join(".");
904 } else if (typeof libraryName === "object") {
905 return getLibraryName(libraryName.root);
906 } else if (typeof libraryName === "string") {
907 return libraryName;
908 }
909 return "";
910 };
911
912 F(output, "uniqueName", () => {
913 const libraryName = getLibraryName(output.library).replace(
914 /^\[(\\*[\w:]+\\*)\](\.)|(\.)\[(\\*[\w:]+\\*)\](?=\.|$)|\[(\\*[\w:]+\\*)\]/g,
915 (m, a, d1, d2, b, c) => {
916 const content = a || b || c;
917 return content.startsWith("\\") && content.endsWith("\\")
918 ? `${d2 || ""}[${content.slice(1, -1)}]${d1 || ""}`
919 : "";
920 }
921 );
922 if (libraryName) return libraryName;
923 const pkgPath = path.resolve(context, "package.json");
924 try {
925 const packageInfo = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
926 return packageInfo.name || "";
927 } catch (err) {
928 if (/** @type {Error & { code: string }} */ (err).code !== "ENOENT") {
929 /** @type {Error & { code: string }} */
930 (err).message +=
931 `\nwhile determining default 'output.uniqueName' from 'name' in ${pkgPath}`;
932 throw err;
933 }
934 return "";
935 }
936 });
937
938 F(output, "module", () => Boolean(outputModule));
939
940 const environment = /** @type {Environment} */ (output.environment);
941 /**
942 * @param {boolean | undefined} v value
943 * @returns {boolean} true, when v is truthy or undefined
944 */
945 const optimistic = v => v || v === undefined;
946 /**
947 * @param {boolean | undefined} v value
948 * @param {boolean | undefined} c condition
949 * @returns {boolean | undefined} true, when v is truthy or undefined, or c is truthy
950 */
951 const conditionallyOptimistic = (v, c) => (v === undefined && c) || v;
952
953 F(
954 environment,
955 "globalThis",
956 () => /** @type {boolean | undefined} */ (tp && tp.globalThis)
957 );
958 F(
959 environment,
960 "bigIntLiteral",
961 () =>
962 tp && optimistic(/** @type {boolean | undefined} */ (tp.bigIntLiteral))
963 );
964 F(
965 environment,
966 "const",
967 () => tp && optimistic(/** @type {boolean | undefined} */ (tp.const))
968 );
969 F(
970 environment,
971 "arrowFunction",
972 () =>
973 tp && optimistic(/** @type {boolean | undefined} */ (tp.arrowFunction))
974 );
975 F(
976 environment,
977 "asyncFunction",
978 () =>
979 tp && optimistic(/** @type {boolean | undefined} */ (tp.asyncFunction))
980 );
981 F(
982 environment,
983 "forOf",
984 () => tp && optimistic(/** @type {boolean | undefined} */ (tp.forOf))
985 );
986 F(
987 environment,
988 "destructuring",
989 () =>
990 tp && optimistic(/** @type {boolean | undefined} */ (tp.destructuring))
991 );
992 F(
993 environment,
994 "optionalChaining",
995 () =>
996 tp && optimistic(/** @type {boolean | undefined} */ (tp.optionalChaining))
997 );
998 F(
999 environment,
1000 "nodePrefixForCoreModules",
1001 () =>
1002 tp &&
1003 optimistic(
1004 /** @type {boolean | undefined} */ (tp.nodePrefixForCoreModules)
1005 )
1006 );
1007 F(
1008 environment,
1009 "templateLiteral",
1010 () =>
1011 tp && optimistic(/** @type {boolean | undefined} */ (tp.templateLiteral))
1012 );
1013 F(environment, "dynamicImport", () =>
1014 conditionallyOptimistic(
1015 /** @type {boolean | undefined} */ (tp && tp.dynamicImport),
1016 output.module
1017 )
1018 );
1019 F(environment, "dynamicImportInWorker", () =>
1020 conditionallyOptimistic(
1021 /** @type {boolean | undefined} */ (tp && tp.dynamicImportInWorker),
1022 output.module
1023 )
1024 );
1025 F(environment, "module", () =>
1026 conditionallyOptimistic(
1027 /** @type {boolean | undefined} */ (tp && tp.module),
1028 output.module
1029 )
1030 );
1031 F(
1032 environment,
1033 "document",
1034 () => tp && optimistic(/** @type {boolean | undefined} */ (tp.document))
1035 );
1036
1037 D(output, "filename", output.module ? "[name].mjs" : "[name].js");
1038 F(output, "iife", () => !output.module);
1039 D(output, "importFunctionName", "import");
1040 D(output, "importMetaName", "import.meta");
1041 F(output, "chunkFilename", () => {
1042 const filename =
1043 /** @type {NonNullable<Output["chunkFilename"]>} */
1044 (output.filename);
1045 if (typeof filename !== "function") {
1046 const hasName = filename.includes("[name]");
1047 const hasId = filename.includes("[id]");
1048 const hasChunkHash = filename.includes("[chunkhash]");
1049 const hasContentHash = filename.includes("[contenthash]");
1050 // Anything changing depending on chunk is fine
1051 if (hasChunkHash || hasContentHash || hasName || hasId) return filename;
1052 // Otherwise prefix "[id]." in front of the basename to make it changing
1053 return filename.replace(/(^|\/)([^/]*(?:\?|$))/, "$1[id].$2");
1054 }
1055 return output.module ? "[id].mjs" : "[id].js";
1056 });
1057 F(output, "cssFilename", () => {
1058 const filename =
1059 /** @type {NonNullable<Output["cssFilename"]>} */
1060 (output.filename);
1061 if (typeof filename !== "function") {
1062 return filename.replace(/\.[mc]?js(\?|$)/, ".css$1");
1063 }
1064 return "[id].css";
1065 });
1066 F(output, "cssChunkFilename", () => {
1067 const chunkFilename =
1068 /** @type {NonNullable<Output["cssChunkFilename"]>} */
1069 (output.chunkFilename);
1070 if (typeof chunkFilename !== "function") {
1071 return chunkFilename.replace(/\.[mc]?js(\?|$)/, ".css$1");
1072 }
1073 return "[id].css";
1074 });
1075 D(output, "assetModuleFilename", "[hash][ext][query]");
1076 D(output, "webassemblyModuleFilename", "[hash].module.wasm");
1077 D(output, "compareBeforeEmit", true);
1078 D(output, "charset", true);
1079 const uniqueNameId = Template.toIdentifier(
1080 /** @type {NonNullable<Output["uniqueName"]>} */ (output.uniqueName)
1081 );
1082 F(output, "hotUpdateGlobal", () => `webpackHotUpdate${uniqueNameId}`);
1083 F(output, "chunkLoadingGlobal", () => `webpackChunk${uniqueNameId}`);
1084 F(output, "globalObject", () => {
1085 if (tp) {
1086 if (tp.global) return "global";
1087 if (tp.globalThis) return "globalThis";
1088 }
1089 return "self";
1090 });
1091 F(output, "chunkFormat", () => {
1092 if (tp) {
1093 const helpMessage = isAffectedByBrowserslist
1094 ? "Make sure that your 'browserslist' includes only platforms that support these features or select an appropriate 'target' to allow selecting a chunk format by default. Alternatively specify the 'output.chunkFormat' directly."
1095 : "Select an appropriate 'target' to allow selecting one by default, or specify the 'output.chunkFormat' directly.";
1096 if (output.module) {
1097 if (environment.dynamicImport) return "module";
1098 if (tp.document) return "array-push";
1099 throw new Error(
1100 "For the selected environment is no default ESM chunk format available:\n" +
1101 "ESM exports can be chosen when 'import()' is available.\n" +
1102 `JSONP Array push can be chosen when 'document' is available.\n${
1103 helpMessage
1104 }`
1105 );
1106 } else {
1107 if (tp.document) return "array-push";
1108 if (tp.require) return "commonjs";
1109 if (tp.nodeBuiltins) return "commonjs";
1110 if (tp.importScripts) return "array-push";
1111 throw new Error(
1112 "For the selected environment is no default script chunk format available:\n" +
1113 "JSONP Array push can be chosen when 'document' or 'importScripts' is available.\n" +
1114 `CommonJs exports can be chosen when 'require' or node builtins are available.\n${
1115 helpMessage
1116 }`
1117 );
1118 }
1119 }
1120 throw new Error(
1121 "Chunk format can't be selected by default when no target is specified"
1122 );
1123 });
1124 D(output, "asyncChunks", true);
1125 F(output, "chunkLoading", () => {
1126 if (tp) {
1127 switch (output.chunkFormat) {
1128 case "array-push":
1129 if (tp.document) return "jsonp";
1130 if (tp.importScripts) return "import-scripts";
1131 break;
1132 case "commonjs":
1133 if (tp.require) return "require";
1134 if (tp.nodeBuiltins) return "async-node";
1135 break;
1136 case "module":
1137 if (environment.dynamicImport) return "import";
1138 break;
1139 }
1140 if (
1141 (tp.require === null ||
1142 tp.nodeBuiltins === null ||
1143 tp.document === null ||
1144 tp.importScripts === null) &&
1145 output.module &&
1146 environment.dynamicImport
1147 ) {
1148 return "universal";
1149 }
1150 }
1151 return false;
1152 });
1153 F(output, "workerChunkLoading", () => {
1154 if (tp) {
1155 switch (output.chunkFormat) {
1156 case "array-push":
1157 if (tp.importScriptsInWorker) return "import-scripts";
1158 break;
1159 case "commonjs":
1160 if (tp.require) return "require";
1161 if (tp.nodeBuiltins) return "async-node";
1162 break;
1163 case "module":
1164 if (environment.dynamicImportInWorker) return "import";
1165 break;
1166 }
1167 if (
1168 (tp.require === null ||
1169 tp.nodeBuiltins === null ||
1170 tp.importScriptsInWorker === null) &&
1171 output.module &&
1172 environment.dynamicImport
1173 ) {
1174 return "universal";
1175 }
1176 }
1177 return false;
1178 });
1179 F(output, "wasmLoading", () => {
1180 if (tp) {
1181 if (tp.fetchWasm) return "fetch";
1182 if (tp.nodeBuiltins) return "async-node";
1183 if (
1184 (tp.nodeBuiltins === null || tp.fetchWasm === null) &&
1185 asyncWebAssembly &&
1186 output.module &&
1187 environment.dynamicImport
1188 ) {
1189 return "universal";
1190 }
1191 }
1192 return false;
1193 });
1194 F(output, "workerWasmLoading", () => output.wasmLoading);
1195 F(output, "devtoolNamespace", () => output.uniqueName);
1196 if (output.library) {
1197 F(output.library, "type", () => (output.module ? "module" : "var"));
1198 }
1199 F(output, "path", () => path.join(process.cwd(), "dist"));
1200 F(output, "pathinfo", () => development);
1201 D(output, "sourceMapFilename", "[file].map[query]");
1202 D(
1203 output,
1204 "hotUpdateChunkFilename",
1205 `[id].[fullhash].hot-update.${output.module ? "mjs" : "js"}`
1206 );
1207 D(output, "hotUpdateMainFilename", "[runtime].[fullhash].hot-update.json");
1208 D(output, "crossOriginLoading", false);
1209 F(output, "scriptType", () => (output.module ? "module" : false));
1210 D(
1211 output,
1212 "publicPath",
1213 (tp && (tp.document || tp.importScripts)) || output.scriptType === "module"
1214 ? "auto"
1215 : ""
1216 );
1217 D(output, "workerPublicPath", "");
1218 D(output, "chunkLoadTimeout", 120000);
1219 D(output, "hashFunction", futureDefaults ? "xxhash64" : "md4");
1220 D(output, "hashDigest", "hex");
1221 D(output, "hashDigestLength", futureDefaults ? 16 : 20);
1222 D(output, "strictModuleErrorHandling", false);
1223 D(output, "strictModuleExceptionHandling", false);
1224
1225 const { trustedTypes } = output;
1226 if (trustedTypes) {
1227 F(
1228 trustedTypes,
1229 "policyName",
1230 () =>
1231 /** @type {NonNullable<Output["uniqueName"]>} */
1232 (output.uniqueName).replace(/[^a-zA-Z0-9\-#=_/@.%]+/g, "_") || "webpack"
1233 );
1234 D(trustedTypes, "onPolicyCreationFailure", "stop");
1235 }
1236
1237 /**
1238 * @param {function(EntryDescription): void} fn iterator
1239 * @returns {void}
1240 */
1241 const forEachEntry = fn => {
1242 for (const name of Object.keys(entry)) {
1243 fn(/** @type {{[k: string] : EntryDescription}} */ (entry)[name]);
1244 }
1245 };
1246 A(output, "enabledLibraryTypes", () => {
1247 /** @type {LibraryType[]} */
1248 const enabledLibraryTypes = [];
1249 if (output.library) {
1250 enabledLibraryTypes.push(output.library.type);
1251 }
1252 forEachEntry(desc => {
1253 if (desc.library) {
1254 enabledLibraryTypes.push(desc.library.type);
1255 }
1256 });
1257 return enabledLibraryTypes;
1258 });
1259
1260 A(output, "enabledChunkLoadingTypes", () => {
1261 const enabledChunkLoadingTypes = new Set();
1262 if (output.chunkLoading) {
1263 enabledChunkLoadingTypes.add(output.chunkLoading);
1264 }
1265 if (output.workerChunkLoading) {
1266 enabledChunkLoadingTypes.add(output.workerChunkLoading);
1267 }
1268 forEachEntry(desc => {
1269 if (desc.chunkLoading) {
1270 enabledChunkLoadingTypes.add(desc.chunkLoading);
1271 }
1272 });
1273 return Array.from(enabledChunkLoadingTypes);
1274 });
1275
1276 A(output, "enabledWasmLoadingTypes", () => {
1277 const enabledWasmLoadingTypes = new Set();
1278 if (output.wasmLoading) {
1279 enabledWasmLoadingTypes.add(output.wasmLoading);
1280 }
1281 if (output.workerWasmLoading) {
1282 enabledWasmLoadingTypes.add(output.workerWasmLoading);
1283 }
1284 forEachEntry(desc => {
1285 if (desc.wasmLoading) {
1286 enabledWasmLoadingTypes.add(desc.wasmLoading);
1287 }
1288 });
1289 return Array.from(enabledWasmLoadingTypes);
1290 });
1291};
1292
1293/**
1294 * @param {ExternalsPresets} externalsPresets options
1295 * @param {object} options options
1296 * @param {TargetProperties | false} options.targetProperties target properties
1297 * @param {boolean} options.buildHttp buildHttp experiment enabled
1298 * @returns {void}
1299 */
1300const applyExternalsPresetsDefaults = (
1301 externalsPresets,
1302 { targetProperties, buildHttp }
1303) => {
1304 D(
1305 externalsPresets,
1306 "web",
1307 /** @type {boolean | undefined} */
1308 (!buildHttp && targetProperties && targetProperties.web)
1309 );
1310 D(
1311 externalsPresets,
1312 "node",
1313 /** @type {boolean | undefined} */
1314 (targetProperties && targetProperties.node)
1315 );
1316 D(
1317 externalsPresets,
1318 "nwjs",
1319 /** @type {boolean | undefined} */
1320 (targetProperties && targetProperties.nwjs)
1321 );
1322 D(
1323 externalsPresets,
1324 "electron",
1325 /** @type {boolean | undefined} */
1326 (targetProperties && targetProperties.electron)
1327 );
1328 D(
1329 externalsPresets,
1330 "electronMain",
1331 /** @type {boolean | undefined} */
1332 (
1333 targetProperties &&
1334 targetProperties.electron &&
1335 targetProperties.electronMain
1336 )
1337 );
1338 D(
1339 externalsPresets,
1340 "electronPreload",
1341 /** @type {boolean | undefined} */
1342 (
1343 targetProperties &&
1344 targetProperties.electron &&
1345 targetProperties.electronPreload
1346 )
1347 );
1348 D(
1349 externalsPresets,
1350 "electronRenderer",
1351 /** @type {boolean | undefined} */
1352 (
1353 targetProperties &&
1354 targetProperties.electron &&
1355 targetProperties.electronRenderer
1356 )
1357 );
1358};
1359
1360/**
1361 * @param {Loader} loader options
1362 * @param {object} options options
1363 * @param {TargetProperties | false} options.targetProperties target properties
1364 * @param {Environment} options.environment environment
1365 * @returns {void}
1366 */
1367const applyLoaderDefaults = (loader, { targetProperties, environment }) => {
1368 F(loader, "target", () => {
1369 if (targetProperties) {
1370 if (targetProperties.electron) {
1371 if (targetProperties.electronMain) return "electron-main";
1372 if (targetProperties.electronPreload) return "electron-preload";
1373 if (targetProperties.electronRenderer) return "electron-renderer";
1374 return "electron";
1375 }
1376 if (targetProperties.nwjs) return "nwjs";
1377 if (targetProperties.node) return "node";
1378 if (targetProperties.web) return "web";
1379 }
1380 });
1381 D(loader, "environment", environment);
1382};
1383
1384/**
1385 * @param {WebpackNode} node options
1386 * @param {object} options options
1387 * @param {TargetProperties | false} options.targetProperties target properties
1388 * @param {boolean} options.futureDefaults is future defaults enabled
1389 * @param {boolean} options.outputModule is output type is module
1390 * @returns {void}
1391 */
1392const applyNodeDefaults = (
1393 node,
1394 { futureDefaults, outputModule, targetProperties }
1395) => {
1396 if (node === false) return;
1397
1398 F(node, "global", () => {
1399 if (targetProperties && targetProperties.global) return false;
1400 // TODO webpack 6 should always default to false
1401 return futureDefaults ? "warn" : true;
1402 });
1403
1404 const handlerForNames = () => {
1405 if (targetProperties && targetProperties.node)
1406 return outputModule ? "node-module" : "eval-only";
1407 // TODO webpack 6 should always default to false
1408 return futureDefaults ? "warn-mock" : "mock";
1409 };
1410
1411 F(node, "__filename", handlerForNames);
1412 F(node, "__dirname", handlerForNames);
1413};
1414
1415/**
1416 * @param {Performance} performance options
1417 * @param {object} options options
1418 * @param {boolean} options.production is production
1419 * @returns {void}
1420 */
1421const applyPerformanceDefaults = (performance, { production }) => {
1422 if (performance === false) return;
1423 D(performance, "maxAssetSize", 250000);
1424 D(performance, "maxEntrypointSize", 250000);
1425 F(performance, "hints", () => (production ? "warning" : false));
1426};
1427
1428/**
1429 * @param {Optimization} optimization options
1430 * @param {object} options options
1431 * @param {boolean} options.production is production
1432 * @param {boolean} options.development is development
1433 * @param {boolean} options.css is css enabled
1434 * @param {boolean} options.records using records
1435 * @returns {void}
1436 */
1437const applyOptimizationDefaults = (
1438 optimization,
1439 { production, development, css, records }
1440) => {
1441 D(optimization, "removeAvailableModules", false);
1442 D(optimization, "removeEmptyChunks", true);
1443 D(optimization, "mergeDuplicateChunks", true);
1444 D(optimization, "flagIncludedChunks", production);
1445 F(optimization, "moduleIds", () => {
1446 if (production) return "deterministic";
1447 if (development) return "named";
1448 return "natural";
1449 });
1450 F(optimization, "chunkIds", () => {
1451 if (production) return "deterministic";
1452 if (development) return "named";
1453 return "natural";
1454 });
1455 F(optimization, "sideEffects", () => (production ? true : "flag"));
1456 D(optimization, "providedExports", true);
1457 D(optimization, "usedExports", production);
1458 D(optimization, "innerGraph", production);
1459 D(optimization, "mangleExports", production);
1460 D(optimization, "concatenateModules", production);
1461 D(optimization, "avoidEntryIife", production);
1462 D(optimization, "runtimeChunk", false);
1463 D(optimization, "emitOnErrors", !production);
1464 D(optimization, "checkWasmTypes", production);
1465 D(optimization, "mangleWasmImports", false);
1466 D(optimization, "portableRecords", records);
1467 D(optimization, "realContentHash", production);
1468 D(optimization, "minimize", production);
1469 A(optimization, "minimizer", () => [
1470 {
1471 apply: compiler => {
1472 // Lazy load the Terser plugin
1473 const TerserPlugin = require("terser-webpack-plugin");
1474 new TerserPlugin({
1475 terserOptions: {
1476 compress: {
1477 passes: 2
1478 }
1479 }
1480 }).apply(compiler);
1481 }
1482 }
1483 ]);
1484 F(optimization, "nodeEnv", () => {
1485 if (production) return "production";
1486 if (development) return "development";
1487 return false;
1488 });
1489 const { splitChunks } = optimization;
1490 if (splitChunks) {
1491 A(splitChunks, "defaultSizeTypes", () =>
1492 css ? ["javascript", "css", "unknown"] : ["javascript", "unknown"]
1493 );
1494 D(splitChunks, "hidePathInfo", production);
1495 D(splitChunks, "chunks", "async");
1496 D(splitChunks, "usedExports", optimization.usedExports === true);
1497 D(splitChunks, "minChunks", 1);
1498 F(splitChunks, "minSize", () => (production ? 20000 : 10000));
1499 F(splitChunks, "minRemainingSize", () => (development ? 0 : undefined));
1500 F(splitChunks, "enforceSizeThreshold", () => (production ? 50000 : 30000));
1501 F(splitChunks, "maxAsyncRequests", () => (production ? 30 : Infinity));
1502 F(splitChunks, "maxInitialRequests", () => (production ? 30 : Infinity));
1503 D(splitChunks, "automaticNameDelimiter", "-");
1504 const cacheGroups =
1505 /** @type {NonNullable<OptimizationSplitChunksOptions["cacheGroups"]>} */
1506 (splitChunks.cacheGroups);
1507 F(cacheGroups, "default", () => ({
1508 idHint: "",
1509 reuseExistingChunk: true,
1510 minChunks: 2,
1511 priority: -20
1512 }));
1513 F(cacheGroups, "defaultVendors", () => ({
1514 idHint: "vendors",
1515 reuseExistingChunk: true,
1516 test: NODE_MODULES_REGEXP,
1517 priority: -10
1518 }));
1519 }
1520};
1521
1522/**
1523 * @param {object} options options
1524 * @param {boolean} options.cache is cache enable
1525 * @param {string} options.context build context
1526 * @param {TargetProperties | false} options.targetProperties target properties
1527 * @param {Mode} options.mode mode
1528 * @param {boolean} options.css is css enabled
1529 * @returns {ResolveOptions} resolve options
1530 */
1531const getResolveDefaults = ({
1532 cache,
1533 context,
1534 targetProperties,
1535 mode,
1536 css
1537}) => {
1538 /** @type {string[]} */
1539 const conditions = ["webpack"];
1540
1541 conditions.push(mode === "development" ? "development" : "production");
1542
1543 if (targetProperties) {
1544 if (targetProperties.webworker) conditions.push("worker");
1545 if (targetProperties.node) conditions.push("node");
1546 if (targetProperties.web) conditions.push("browser");
1547 if (targetProperties.electron) conditions.push("electron");
1548 if (targetProperties.nwjs) conditions.push("nwjs");
1549 }
1550
1551 const jsExtensions = [".js", ".json", ".wasm"];
1552
1553 const tp = targetProperties;
1554 const browserField =
1555 tp && tp.web && (!tp.node || (tp.electron && tp.electronRenderer));
1556
1557 /** @type {function(): ResolveOptions} */
1558 const cjsDeps = () => ({
1559 aliasFields: browserField ? ["browser"] : [],
1560 mainFields: browserField ? ["browser", "module", "..."] : ["module", "..."],
1561 conditionNames: ["require", "module", "..."],
1562 extensions: [...jsExtensions]
1563 });
1564 /** @type {function(): ResolveOptions} */
1565 const esmDeps = () => ({
1566 aliasFields: browserField ? ["browser"] : [],
1567 mainFields: browserField ? ["browser", "module", "..."] : ["module", "..."],
1568 conditionNames: ["import", "module", "..."],
1569 extensions: [...jsExtensions]
1570 });
1571
1572 /** @type {ResolveOptions} */
1573 const resolveOptions = {
1574 cache,
1575 modules: ["node_modules"],
1576 conditionNames: conditions,
1577 mainFiles: ["index"],
1578 extensions: [],
1579 aliasFields: [],
1580 exportsFields: ["exports"],
1581 roots: [context],
1582 mainFields: ["main"],
1583 importsFields: ["imports"],
1584 byDependency: {
1585 wasm: esmDeps(),
1586 esm: esmDeps(),
1587 loaderImport: esmDeps(),
1588 url: {
1589 preferRelative: true
1590 },
1591 worker: {
1592 ...esmDeps(),
1593 preferRelative: true
1594 },
1595 commonjs: cjsDeps(),
1596 amd: cjsDeps(),
1597 // for backward-compat: loadModule
1598 loader: cjsDeps(),
1599 // for backward-compat: Custom Dependency
1600 unknown: cjsDeps(),
1601 // for backward-compat: getResolve without dependencyType
1602 undefined: cjsDeps()
1603 }
1604 };
1605
1606 if (css) {
1607 const styleConditions = [];
1608
1609 styleConditions.push("webpack");
1610 styleConditions.push(mode === "development" ? "development" : "production");
1611 styleConditions.push("style");
1612
1613 resolveOptions.byDependency["css-import"] = {
1614 // We avoid using any main files because we have to be consistent with CSS `@import`
1615 // and CSS `@import` does not handle `main` files in directories,
1616 // you should always specify the full URL for styles
1617 mainFiles: [],
1618 mainFields: ["style", "..."],
1619 conditionNames: styleConditions,
1620 extensions: [".css"],
1621 preferRelative: true
1622 };
1623 }
1624
1625 return resolveOptions;
1626};
1627
1628/**
1629 * @param {object} options options
1630 * @param {boolean} options.cache is cache enable
1631 * @returns {ResolveOptions} resolve options
1632 */
1633const getResolveLoaderDefaults = ({ cache }) => {
1634 /** @type {ResolveOptions} */
1635 const resolveOptions = {
1636 cache,
1637 conditionNames: ["loader", "require", "node"],
1638 exportsFields: ["exports"],
1639 mainFields: ["loader", "main"],
1640 extensions: [".js"],
1641 mainFiles: ["index"]
1642 };
1643
1644 return resolveOptions;
1645};
1646
1647/**
1648 * @param {InfrastructureLogging} infrastructureLogging options
1649 * @returns {void}
1650 */
1651const applyInfrastructureLoggingDefaults = infrastructureLogging => {
1652 F(infrastructureLogging, "stream", () => process.stderr);
1653 const tty =
1654 /** @type {any} */ (infrastructureLogging.stream).isTTY &&
1655 process.env.TERM !== "dumb";
1656 D(infrastructureLogging, "level", "info");
1657 D(infrastructureLogging, "debug", false);
1658 D(infrastructureLogging, "colors", tty);
1659 D(infrastructureLogging, "appendOnly", !tty);
1660};
1661
1662module.exports.applyWebpackOptionsBaseDefaults =
1663 applyWebpackOptionsBaseDefaults;
1664module.exports.applyWebpackOptionsDefaults = applyWebpackOptionsDefaults;
Note: See TracBrowser for help on using the repository browser.