source: trip-planner-front/node_modules/webpack/lib/config/defaults.js@ 188ee53

Last change on this file since 188ee53 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 33.5 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 Template = require("../Template");
11const { cleverMerge } = require("../util/cleverMerge");
12const {
13 getTargetsProperties,
14 getTargetProperties,
15 getDefaultTarget
16} = require("./target");
17
18/** @typedef {import("../../declarations/WebpackOptions").CacheOptionsNormalized} CacheOptions */
19/** @typedef {import("../../declarations/WebpackOptions").EntryDescription} EntryDescription */
20/** @typedef {import("../../declarations/WebpackOptions").EntryNormalized} Entry */
21/** @typedef {import("../../declarations/WebpackOptions").Experiments} Experiments */
22/** @typedef {import("../../declarations/WebpackOptions").ExternalsPresets} ExternalsPresets */
23/** @typedef {import("../../declarations/WebpackOptions").ExternalsType} ExternalsType */
24/** @typedef {import("../../declarations/WebpackOptions").InfrastructureLogging} InfrastructureLogging */
25/** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */
26/** @typedef {import("../../declarations/WebpackOptions").Library} Library */
27/** @typedef {import("../../declarations/WebpackOptions").LibraryName} LibraryName */
28/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */
29/** @typedef {import("../../declarations/WebpackOptions").Loader} Loader */
30/** @typedef {import("../../declarations/WebpackOptions").Mode} Mode */
31/** @typedef {import("../../declarations/WebpackOptions").ModuleOptionsNormalized} ModuleOptions */
32/** @typedef {import("../../declarations/WebpackOptions").Node} WebpackNode */
33/** @typedef {import("../../declarations/WebpackOptions").Optimization} Optimization */
34/** @typedef {import("../../declarations/WebpackOptions").OutputNormalized} Output */
35/** @typedef {import("../../declarations/WebpackOptions").Performance} Performance */
36/** @typedef {import("../../declarations/WebpackOptions").ResolveOptions} ResolveOptions */
37/** @typedef {import("../../declarations/WebpackOptions").RuleSetRules} RuleSetRules */
38/** @typedef {import("../../declarations/WebpackOptions").SnapshotOptions} SnapshotOptions */
39/** @typedef {import("../../declarations/WebpackOptions").Target} Target */
40/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */
41/** @typedef {import("./target").TargetProperties} TargetProperties */
42
43const NODE_MODULES_REGEXP = /[\\/]node_modules[\\/]/i;
44
45/**
46 * Sets a constant default value when undefined
47 * @template T
48 * @template {keyof T} P
49 * @param {T} obj an object
50 * @param {P} prop a property of this object
51 * @param {T[P]} value a default value of the property
52 * @returns {void}
53 */
54const D = (obj, prop, value) => {
55 if (obj[prop] === undefined) {
56 obj[prop] = value;
57 }
58};
59
60/**
61 * Sets a dynamic default value when undefined, by calling the factory function
62 * @template T
63 * @template {keyof T} P
64 * @param {T} obj an object
65 * @param {P} prop a property of this object
66 * @param {function(): T[P]} factory a default value factory for the property
67 * @returns {void}
68 */
69const F = (obj, prop, factory) => {
70 if (obj[prop] === undefined) {
71 obj[prop] = factory();
72 }
73};
74
75/**
76 * Sets a dynamic default value when undefined, by calling the factory function.
77 * factory must return an array or undefined
78 * When the current value is already an array an contains "..." it's replaced with
79 * the result of the factory function
80 * @template T
81 * @template {keyof T} P
82 * @param {T} obj an object
83 * @param {P} prop a property of this object
84 * @param {function(): T[P]} factory a default value factory for the property
85 * @returns {void}
86 */
87const A = (obj, prop, factory) => {
88 const value = obj[prop];
89 if (value === undefined) {
90 obj[prop] = factory();
91 } else if (Array.isArray(value)) {
92 /** @type {any[]} */
93 let newArray = undefined;
94 for (let i = 0; i < value.length; i++) {
95 const item = value[i];
96 if (item === "...") {
97 if (newArray === undefined) {
98 newArray = value.slice(0, i);
99 obj[prop] = /** @type {T[P]} */ (/** @type {unknown} */ (newArray));
100 }
101 const items = /** @type {any[]} */ (/** @type {unknown} */ (factory()));
102 if (items !== undefined) {
103 for (const item of items) {
104 newArray.push(item);
105 }
106 }
107 } else if (newArray !== undefined) {
108 newArray.push(item);
109 }
110 }
111 }
112};
113
114/**
115 * @param {WebpackOptions} options options to be modified
116 * @returns {void}
117 */
118const applyWebpackOptionsBaseDefaults = options => {
119 F(options, "context", () => process.cwd());
120 applyInfrastructureLoggingDefaults(options.infrastructureLogging);
121};
122
123/**
124 * @param {WebpackOptions} options options to be modified
125 * @returns {void}
126 */
127const applyWebpackOptionsDefaults = options => {
128 F(options, "context", () => process.cwd());
129 F(options, "target", () => {
130 return getDefaultTarget(options.context);
131 });
132
133 const { mode, name, target } = options;
134
135 let targetProperties =
136 target === false
137 ? /** @type {false} */ (false)
138 : typeof target === "string"
139 ? getTargetProperties(target, options.context)
140 : getTargetsProperties(target, options.context);
141
142 const development = mode === "development";
143 const production = mode === "production" || !mode;
144
145 if (typeof options.entry !== "function") {
146 for (const key of Object.keys(options.entry)) {
147 F(
148 options.entry[key],
149 "import",
150 () => /** @type {[string]} */ (["./src"])
151 );
152 }
153 }
154
155 F(options, "devtool", () => (development ? "eval" : false));
156 D(options, "watch", false);
157 D(options, "profile", false);
158 D(options, "parallelism", 100);
159 D(options, "recordsInputPath", false);
160 D(options, "recordsOutputPath", false);
161
162 F(options, "cache", () =>
163 development ? { type: /** @type {"memory"} */ ("memory") } : false
164 );
165 applyCacheDefaults(options.cache, {
166 name: name || "default",
167 mode: mode || "production",
168 development
169 });
170 const cache = !!options.cache;
171
172 applySnapshotDefaults(options.snapshot, { production });
173
174 applyExperimentsDefaults(options.experiments, { production, development });
175
176 applyModuleDefaults(options.module, {
177 cache,
178 syncWebAssembly: options.experiments.syncWebAssembly,
179 asyncWebAssembly: options.experiments.asyncWebAssembly
180 });
181
182 applyOutputDefaults(options.output, {
183 context: options.context,
184 targetProperties,
185 isAffectedByBrowserslist:
186 target === undefined ||
187 (typeof target === "string" && target.startsWith("browserslist")) ||
188 (Array.isArray(target) &&
189 target.some(target => target.startsWith("browserslist"))),
190 outputModule: options.experiments.outputModule,
191 development,
192 entry: options.entry,
193 module: options.module
194 });
195
196 applyExternalsPresetsDefaults(options.externalsPresets, {
197 targetProperties,
198 buildHttp: !!options.experiments.buildHttp
199 });
200
201 applyLoaderDefaults(options.loader, { targetProperties });
202
203 F(options, "externalsType", () => {
204 const validExternalTypes = require("../../schemas/WebpackOptions.json")
205 .definitions.ExternalsType.enum;
206 return options.output.library &&
207 validExternalTypes.includes(options.output.library.type)
208 ? /** @type {ExternalsType} */ (options.output.library.type)
209 : options.output.module
210 ? "module"
211 : "var";
212 });
213
214 applyNodeDefaults(options.node, { targetProperties });
215
216 F(options, "performance", () =>
217 production &&
218 targetProperties &&
219 (targetProperties.browser || targetProperties.browser === null)
220 ? {}
221 : false
222 );
223 applyPerformanceDefaults(options.performance, {
224 production
225 });
226
227 applyOptimizationDefaults(options.optimization, {
228 development,
229 production,
230 records: !!(options.recordsInputPath || options.recordsOutputPath)
231 });
232
233 options.resolve = cleverMerge(
234 getResolveDefaults({
235 cache,
236 context: options.context,
237 targetProperties,
238 mode: options.mode
239 }),
240 options.resolve
241 );
242
243 options.resolveLoader = cleverMerge(
244 getResolveLoaderDefaults({ cache }),
245 options.resolveLoader
246 );
247};
248
249/**
250 * @param {Experiments} experiments options
251 * @param {Object} options options
252 * @param {boolean} options.production is production
253 * @param {boolean} options.development is development mode
254 * @returns {void}
255 */
256const applyExperimentsDefaults = (experiments, { production, development }) => {
257 D(experiments, "topLevelAwait", false);
258 D(experiments, "syncWebAssembly", false);
259 D(experiments, "asyncWebAssembly", false);
260 D(experiments, "outputModule", false);
261 D(experiments, "asset", false);
262 D(experiments, "executeModule", false);
263 D(experiments, "layers", false);
264 D(experiments, "lazyCompilation", false);
265 D(experiments, "buildHttp", false);
266
267 if (typeof experiments.buildHttp === "object") {
268 D(experiments.buildHttp, "frozen", production);
269 D(experiments.buildHttp, "upgrade", development);
270 }
271};
272
273/**
274 * @param {CacheOptions} cache options
275 * @param {Object} options options
276 * @param {string} options.name name
277 * @param {string} options.mode mode
278 * @param {boolean} options.development is development mode
279 * @returns {void}
280 */
281const applyCacheDefaults = (cache, { name, mode, development }) => {
282 if (cache === false) return;
283 switch (cache.type) {
284 case "filesystem":
285 F(cache, "name", () => name + "-" + mode);
286 D(cache, "version", "");
287 F(cache, "cacheDirectory", () => {
288 const cwd = process.cwd();
289 let dir = cwd;
290 for (;;) {
291 try {
292 if (fs.statSync(path.join(dir, "package.json")).isFile()) break;
293 // eslint-disable-next-line no-empty
294 } catch (e) {}
295 const parent = path.dirname(dir);
296 if (dir === parent) {
297 dir = undefined;
298 break;
299 }
300 dir = parent;
301 }
302 if (!dir) {
303 return path.resolve(cwd, ".cache/webpack");
304 } else if (process.versions.pnp === "1") {
305 return path.resolve(dir, ".pnp/.cache/webpack");
306 } else if (process.versions.pnp === "3") {
307 return path.resolve(dir, ".yarn/.cache/webpack");
308 } else {
309 return path.resolve(dir, "node_modules/.cache/webpack");
310 }
311 });
312 F(cache, "cacheLocation", () =>
313 path.resolve(cache.cacheDirectory, cache.name)
314 );
315 D(cache, "hashAlgorithm", "md4");
316 D(cache, "store", "pack");
317 D(cache, "compression", false);
318 D(cache, "profile", false);
319 D(cache, "idleTimeout", 60000);
320 D(cache, "idleTimeoutForInitialStore", 5000);
321 D(cache, "idleTimeoutAfterLargeChanges", 1000);
322 D(cache, "maxMemoryGenerations", development ? 5 : Infinity);
323 D(cache, "maxAge", 1000 * 60 * 60 * 24 * 60); // 1 month
324 D(cache, "allowCollectingMemory", development);
325 D(cache.buildDependencies, "defaultWebpack", [
326 path.resolve(__dirname, "..") + path.sep
327 ]);
328 break;
329 case "memory":
330 D(cache, "maxGenerations", Infinity);
331 break;
332 }
333};
334
335/**
336 * @param {SnapshotOptions} snapshot options
337 * @param {Object} options options
338 * @param {boolean} options.production is production
339 * @returns {void}
340 */
341const applySnapshotDefaults = (snapshot, { production }) => {
342 A(snapshot, "managedPaths", () => {
343 if (process.versions.pnp === "3") {
344 const match =
345 /^(.+?)[\\/]cache[\\/]watchpack-npm-[^\\/]+\.zip[\\/]node_modules[\\/]/.exec(
346 require.resolve("watchpack")
347 );
348 if (match) {
349 return [path.resolve(match[1], "unplugged")];
350 }
351 } else {
352 const match = /^(.+?[\\/]node_modules)[\\/]/.exec(
353 // eslint-disable-next-line node/no-extraneous-require
354 require.resolve("watchpack")
355 );
356 if (match) {
357 return [match[1]];
358 }
359 }
360 return [];
361 });
362 A(snapshot, "immutablePaths", () => {
363 if (process.versions.pnp === "1") {
364 const match =
365 /^(.+?[\\/]v4)[\\/]npm-watchpack-[^\\/]+-[\da-f]{40}[\\/]node_modules[\\/]/.exec(
366 require.resolve("watchpack")
367 );
368 if (match) {
369 return [match[1]];
370 }
371 } else if (process.versions.pnp === "3") {
372 const match =
373 /^(.+?)[\\/]watchpack-npm-[^\\/]+\.zip[\\/]node_modules[\\/]/.exec(
374 require.resolve("watchpack")
375 );
376 if (match) {
377 return [match[1]];
378 }
379 }
380 return [];
381 });
382 F(snapshot, "resolveBuildDependencies", () => ({
383 timestamp: true,
384 hash: true
385 }));
386 F(snapshot, "buildDependencies", () => ({ timestamp: true, hash: true }));
387 F(snapshot, "module", () =>
388 production ? { timestamp: true, hash: true } : { timestamp: true }
389 );
390 F(snapshot, "resolve", () =>
391 production ? { timestamp: true, hash: true } : { timestamp: true }
392 );
393};
394
395/**
396 * @param {JavascriptParserOptions} parserOptions parser options
397 * @returns {void}
398 */
399const applyJavascriptParserOptionsDefaults = parserOptions => {
400 D(parserOptions, "unknownContextRequest", ".");
401 D(parserOptions, "unknownContextRegExp", false);
402 D(parserOptions, "unknownContextRecursive", true);
403 D(parserOptions, "unknownContextCritical", true);
404 D(parserOptions, "exprContextRequest", ".");
405 D(parserOptions, "exprContextRegExp", false);
406 D(parserOptions, "exprContextRecursive", true);
407 D(parserOptions, "exprContextCritical", true);
408 D(parserOptions, "wrappedContextRegExp", /.*/);
409 D(parserOptions, "wrappedContextRecursive", true);
410 D(parserOptions, "wrappedContextCritical", false);
411
412 D(parserOptions, "strictExportPresence", false);
413 D(parserOptions, "strictThisContextOnImports", false);
414};
415
416/**
417 * @param {ModuleOptions} module options
418 * @param {Object} options options
419 * @param {boolean} options.cache is caching enabled
420 * @param {boolean} options.syncWebAssembly is syncWebAssembly enabled
421 * @param {boolean} options.asyncWebAssembly is asyncWebAssembly enabled
422 * @returns {void}
423 */
424const applyModuleDefaults = (
425 module,
426 { cache, syncWebAssembly, asyncWebAssembly }
427) => {
428 if (cache) {
429 D(module, "unsafeCache", module => {
430 const name = module.nameForCondition();
431 return name && NODE_MODULES_REGEXP.test(name);
432 });
433 } else {
434 D(module, "unsafeCache", false);
435 }
436
437 F(module.parser, "asset", () => ({}));
438 F(module.parser.asset, "dataUrlCondition", () => ({}));
439 if (typeof module.parser.asset.dataUrlCondition === "object") {
440 D(module.parser.asset.dataUrlCondition, "maxSize", 8096);
441 }
442
443 F(module.parser, "javascript", () => ({}));
444 applyJavascriptParserOptionsDefaults(module.parser.javascript);
445
446 A(module, "defaultRules", () => {
447 const esm = {
448 type: "javascript/esm",
449 resolve: {
450 byDependency: {
451 esm: {
452 fullySpecified: true
453 }
454 }
455 }
456 };
457 const commonjs = {
458 type: "javascript/dynamic"
459 };
460 /** @type {RuleSetRules} */
461 const rules = [
462 {
463 mimetype: "application/node",
464 type: "javascript/auto"
465 },
466 {
467 test: /\.json$/i,
468 type: "json"
469 },
470 {
471 mimetype: "application/json",
472 type: "json"
473 },
474 {
475 test: /\.mjs$/i,
476 ...esm
477 },
478 {
479 test: /\.js$/i,
480 descriptionData: {
481 type: "module"
482 },
483 ...esm
484 },
485 {
486 test: /\.cjs$/i,
487 ...commonjs
488 },
489 {
490 test: /\.js$/i,
491 descriptionData: {
492 type: "commonjs"
493 },
494 ...commonjs
495 },
496 {
497 mimetype: {
498 or: ["text/javascript", "application/javascript"]
499 },
500 ...esm
501 }
502 ];
503 if (asyncWebAssembly) {
504 const wasm = {
505 type: "webassembly/async",
506 rules: [
507 {
508 descriptionData: {
509 type: "module"
510 },
511 resolve: {
512 fullySpecified: true
513 }
514 }
515 ]
516 };
517 rules.push({
518 test: /\.wasm$/i,
519 ...wasm
520 });
521 rules.push({
522 mimetype: "application/wasm",
523 ...wasm
524 });
525 } else if (syncWebAssembly) {
526 const wasm = {
527 type: "webassembly/sync",
528 rules: [
529 {
530 descriptionData: {
531 type: "module"
532 },
533 resolve: {
534 fullySpecified: true
535 }
536 }
537 ]
538 };
539 rules.push({
540 test: /\.wasm$/i,
541 ...wasm
542 });
543 rules.push({
544 mimetype: "application/wasm",
545 ...wasm
546 });
547 }
548 rules.push(
549 {
550 dependency: "url",
551 oneOf: [
552 {
553 scheme: /^data$/,
554 type: "asset/inline"
555 },
556 {
557 type: "asset/resource"
558 }
559 ]
560 },
561 {
562 assert: { type: "json" },
563 type: "json"
564 }
565 );
566 return rules;
567 });
568};
569
570/**
571 * @param {Output} output options
572 * @param {Object} options options
573 * @param {string} options.context context
574 * @param {TargetProperties | false} options.targetProperties target properties
575 * @param {boolean} options.isAffectedByBrowserslist is affected by browserslist
576 * @param {boolean} options.outputModule is outputModule experiment enabled
577 * @param {boolean} options.development is development mode
578 * @param {Entry} options.entry entry option
579 * @param {ModuleOptions} options.module module option
580 * @returns {void}
581 */
582const applyOutputDefaults = (
583 output,
584 {
585 context,
586 targetProperties: tp,
587 isAffectedByBrowserslist,
588 outputModule,
589 development,
590 entry,
591 module
592 }
593) => {
594 /**
595 * @param {Library=} library the library option
596 * @returns {string} a readable library name
597 */
598 const getLibraryName = library => {
599 const libraryName =
600 typeof library === "object" &&
601 library &&
602 !Array.isArray(library) &&
603 "type" in library
604 ? library.name
605 : /** @type {LibraryName=} */ (library);
606 if (Array.isArray(libraryName)) {
607 return libraryName.join(".");
608 } else if (typeof libraryName === "object") {
609 return getLibraryName(libraryName.root);
610 } else if (typeof libraryName === "string") {
611 return libraryName;
612 }
613 return "";
614 };
615
616 F(output, "uniqueName", () => {
617 const libraryName = getLibraryName(output.library);
618 if (libraryName) return libraryName;
619 const pkgPath = path.resolve(context, "package.json");
620 try {
621 const packageInfo = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
622 return packageInfo.name || "";
623 } catch (e) {
624 if (e.code !== "ENOENT") {
625 e.message += `\nwhile determining default 'output.uniqueName' from 'name' in ${pkgPath}`;
626 throw e;
627 }
628 return "";
629 }
630 });
631
632 F(output, "module", () => !!outputModule);
633 D(output, "filename", output.module ? "[name].mjs" : "[name].js");
634 F(output, "iife", () => !output.module);
635 D(output, "importFunctionName", "import");
636 D(output, "importMetaName", "import.meta");
637 F(output, "chunkFilename", () => {
638 const filename = output.filename;
639 if (typeof filename !== "function") {
640 const hasName = filename.includes("[name]");
641 const hasId = filename.includes("[id]");
642 const hasChunkHash = filename.includes("[chunkhash]");
643 const hasContentHash = filename.includes("[contenthash]");
644 // Anything changing depending on chunk is fine
645 if (hasChunkHash || hasContentHash || hasName || hasId) return filename;
646 // Otherwise prefix "[id]." in front of the basename to make it changing
647 return filename.replace(/(^|\/)([^/]*(?:\?|$))/, "$1[id].$2");
648 }
649 return output.module ? "[id].mjs" : "[id].js";
650 });
651 D(output, "assetModuleFilename", "[hash][ext][query]");
652 D(output, "webassemblyModuleFilename", "[hash].module.wasm");
653 D(output, "compareBeforeEmit", true);
654 D(output, "charset", true);
655 F(output, "hotUpdateGlobal", () =>
656 Template.toIdentifier(
657 "webpackHotUpdate" + Template.toIdentifier(output.uniqueName)
658 )
659 );
660 F(output, "chunkLoadingGlobal", () =>
661 Template.toIdentifier(
662 "webpackChunk" + Template.toIdentifier(output.uniqueName)
663 )
664 );
665 F(output, "globalObject", () => {
666 if (tp) {
667 if (tp.global) return "global";
668 if (tp.globalThis) return "globalThis";
669 }
670 return "self";
671 });
672 F(output, "chunkFormat", () => {
673 if (tp) {
674 const helpMessage = isAffectedByBrowserslist
675 ? "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."
676 : "Select an appropriate 'target' to allow selecting one by default, or specify the 'output.chunkFormat' directly.";
677 if (output.module) {
678 if (tp.dynamicImport) return "module";
679 if (tp.document) return "array-push";
680 throw new Error(
681 "For the selected environment is no default ESM chunk format available:\n" +
682 "ESM exports can be chosen when 'import()' is available.\n" +
683 "JSONP Array push can be chosen when 'document' is available.\n" +
684 helpMessage
685 );
686 } else {
687 if (tp.document) return "array-push";
688 if (tp.require) return "commonjs";
689 if (tp.nodeBuiltins) return "commonjs";
690 if (tp.importScripts) return "array-push";
691 throw new Error(
692 "For the selected environment is no default script chunk format available:\n" +
693 "JSONP Array push can be chosen when 'document' or 'importScripts' is available.\n" +
694 "CommonJs exports can be chosen when 'require' or node builtins are available.\n" +
695 helpMessage
696 );
697 }
698 }
699 throw new Error(
700 "Chunk format can't be selected by default when no target is specified"
701 );
702 });
703 F(output, "chunkLoading", () => {
704 if (tp) {
705 switch (output.chunkFormat) {
706 case "array-push":
707 if (tp.document) return "jsonp";
708 if (tp.importScripts) return "import-scripts";
709 break;
710 case "commonjs":
711 if (tp.require) return "require";
712 if (tp.nodeBuiltins) return "async-node";
713 break;
714 case "module":
715 if (tp.dynamicImport) return "import";
716 break;
717 }
718 if (
719 tp.require === null ||
720 tp.nodeBuiltins === null ||
721 tp.document === null ||
722 tp.importScripts === null
723 ) {
724 return "universal";
725 }
726 }
727 return false;
728 });
729 F(output, "workerChunkLoading", () => {
730 if (tp) {
731 switch (output.chunkFormat) {
732 case "array-push":
733 if (tp.importScriptsInWorker) return "import-scripts";
734 break;
735 case "commonjs":
736 if (tp.require) return "require";
737 if (tp.nodeBuiltins) return "async-node";
738 break;
739 case "module":
740 if (tp.dynamicImportInWorker) return "import";
741 break;
742 }
743 if (
744 tp.require === null ||
745 tp.nodeBuiltins === null ||
746 tp.importScriptsInWorker === null
747 ) {
748 return "universal";
749 }
750 }
751 return false;
752 });
753 F(output, "wasmLoading", () => {
754 if (tp) {
755 if (tp.fetchWasm) return "fetch";
756 if (tp.nodeBuiltins)
757 return output.module ? "async-node-module" : "async-node";
758 if (tp.nodeBuiltins === null || tp.fetchWasm === null) {
759 return "universal";
760 }
761 }
762 return false;
763 });
764 F(output, "workerWasmLoading", () => output.wasmLoading);
765 F(output, "devtoolNamespace", () => output.uniqueName);
766 if (output.library) {
767 F(output.library, "type", () => (output.module ? "module" : "var"));
768 }
769 F(output, "path", () => path.join(process.cwd(), "dist"));
770 F(output, "pathinfo", () => development);
771 D(output, "sourceMapFilename", "[file].map[query]");
772 D(
773 output,
774 "hotUpdateChunkFilename",
775 `[id].[fullhash].hot-update.${output.module ? "mjs" : "js"}`
776 );
777 D(output, "hotUpdateMainFilename", "[runtime].[fullhash].hot-update.json");
778 D(output, "crossOriginLoading", false);
779 F(output, "scriptType", () => (output.module ? "module" : false));
780 D(
781 output,
782 "publicPath",
783 (tp && (tp.document || tp.importScripts)) || output.scriptType === "module"
784 ? "auto"
785 : ""
786 );
787 D(output, "chunkLoadTimeout", 120000);
788 D(output, "hashFunction", "md4");
789 D(output, "hashDigest", "hex");
790 D(output, "hashDigestLength", 20);
791 D(output, "strictModuleExceptionHandling", false);
792
793 const optimistic = v => v || v === undefined;
794 F(
795 output.environment,
796 "arrowFunction",
797 () => tp && optimistic(tp.arrowFunction)
798 );
799 F(output.environment, "const", () => tp && optimistic(tp.const));
800 F(
801 output.environment,
802 "destructuring",
803 () => tp && optimistic(tp.destructuring)
804 );
805 F(output.environment, "forOf", () => tp && optimistic(tp.forOf));
806 F(output.environment, "bigIntLiteral", () => tp && tp.bigIntLiteral);
807 F(output.environment, "dynamicImport", () => tp && tp.dynamicImport);
808 F(output.environment, "module", () => tp && tp.module);
809
810 const { trustedTypes } = output;
811 if (trustedTypes) {
812 F(
813 trustedTypes,
814 "policyName",
815 () =>
816 output.uniqueName.replace(/[^a-zA-Z0-9\-#=_/@.%]+/g, "_") || "webpack"
817 );
818 }
819
820 /**
821 * @param {function(EntryDescription): void} fn iterator
822 * @returns {void}
823 */
824 const forEachEntry = fn => {
825 for (const name of Object.keys(entry)) {
826 fn(entry[name]);
827 }
828 };
829 A(output, "enabledLibraryTypes", () => {
830 const enabledLibraryTypes = [];
831 if (output.library) {
832 enabledLibraryTypes.push(output.library.type);
833 }
834 forEachEntry(desc => {
835 if (desc.library) {
836 enabledLibraryTypes.push(desc.library.type);
837 }
838 });
839 return enabledLibraryTypes;
840 });
841
842 A(output, "enabledChunkLoadingTypes", () => {
843 const enabledChunkLoadingTypes = new Set();
844 if (output.chunkLoading) {
845 enabledChunkLoadingTypes.add(output.chunkLoading);
846 }
847 if (output.workerChunkLoading) {
848 enabledChunkLoadingTypes.add(output.workerChunkLoading);
849 }
850 forEachEntry(desc => {
851 if (desc.chunkLoading) {
852 enabledChunkLoadingTypes.add(desc.chunkLoading);
853 }
854 });
855 return Array.from(enabledChunkLoadingTypes);
856 });
857
858 A(output, "enabledWasmLoadingTypes", () => {
859 const enabledWasmLoadingTypes = new Set();
860 if (output.wasmLoading) {
861 enabledWasmLoadingTypes.add(output.wasmLoading);
862 }
863 if (output.workerWasmLoading) {
864 enabledWasmLoadingTypes.add(output.workerWasmLoading);
865 }
866 forEachEntry(desc => {
867 if (desc.wasmLoading) {
868 enabledWasmLoadingTypes.add(desc.wasmLoading);
869 }
870 });
871 return Array.from(enabledWasmLoadingTypes);
872 });
873};
874
875/**
876 * @param {ExternalsPresets} externalsPresets options
877 * @param {Object} options options
878 * @param {TargetProperties | false} options.targetProperties target properties
879 * @param {boolean} options.buildHttp buildHttp experiment enabled
880 * @returns {void}
881 */
882const applyExternalsPresetsDefaults = (
883 externalsPresets,
884 { targetProperties, buildHttp }
885) => {
886 D(
887 externalsPresets,
888 "web",
889 !buildHttp && targetProperties && targetProperties.web
890 );
891 D(externalsPresets, "node", targetProperties && targetProperties.node);
892 D(externalsPresets, "nwjs", targetProperties && targetProperties.nwjs);
893 D(
894 externalsPresets,
895 "electron",
896 targetProperties && targetProperties.electron
897 );
898 D(
899 externalsPresets,
900 "electronMain",
901 targetProperties &&
902 targetProperties.electron &&
903 targetProperties.electronMain
904 );
905 D(
906 externalsPresets,
907 "electronPreload",
908 targetProperties &&
909 targetProperties.electron &&
910 targetProperties.electronPreload
911 );
912 D(
913 externalsPresets,
914 "electronRenderer",
915 targetProperties &&
916 targetProperties.electron &&
917 targetProperties.electronRenderer
918 );
919};
920
921/**
922 * @param {Loader} loader options
923 * @param {Object} options options
924 * @param {TargetProperties | false} options.targetProperties target properties
925 * @returns {void}
926 */
927const applyLoaderDefaults = (loader, { targetProperties }) => {
928 F(loader, "target", () => {
929 if (targetProperties) {
930 if (targetProperties.electron) {
931 if (targetProperties.electronMain) return "electron-main";
932 if (targetProperties.electronPreload) return "electron-preload";
933 if (targetProperties.electronRenderer) return "electron-renderer";
934 return "electron";
935 }
936 if (targetProperties.nwjs) return "nwjs";
937 if (targetProperties.node) return "node";
938 if (targetProperties.web) return "web";
939 }
940 });
941};
942
943/**
944 * @param {WebpackNode} node options
945 * @param {Object} options options
946 * @param {TargetProperties | false} options.targetProperties target properties
947 * @returns {void}
948 */
949const applyNodeDefaults = (node, { targetProperties }) => {
950 if (node === false) return;
951 F(node, "global", () => {
952 if (targetProperties && targetProperties.global) return false;
953 return true;
954 });
955 F(node, "__filename", () => {
956 if (targetProperties && targetProperties.node) return "eval-only";
957 return "mock";
958 });
959 F(node, "__dirname", () => {
960 if (targetProperties && targetProperties.node) return "eval-only";
961 return "mock";
962 });
963};
964
965/**
966 * @param {Performance} performance options
967 * @param {Object} options options
968 * @param {boolean} options.production is production
969 * @returns {void}
970 */
971const applyPerformanceDefaults = (performance, { production }) => {
972 if (performance === false) return;
973 D(performance, "maxAssetSize", 250000);
974 D(performance, "maxEntrypointSize", 250000);
975 F(performance, "hints", () => (production ? "warning" : false));
976};
977
978/**
979 * @param {Optimization} optimization options
980 * @param {Object} options options
981 * @param {boolean} options.production is production
982 * @param {boolean} options.development is development
983 * @param {boolean} options.records using records
984 * @returns {void}
985 */
986const applyOptimizationDefaults = (
987 optimization,
988 { production, development, records }
989) => {
990 D(optimization, "removeAvailableModules", false);
991 D(optimization, "removeEmptyChunks", true);
992 D(optimization, "mergeDuplicateChunks", true);
993 D(optimization, "flagIncludedChunks", production);
994 F(optimization, "moduleIds", () => {
995 if (production) return "deterministic";
996 if (development) return "named";
997 return "natural";
998 });
999 F(optimization, "chunkIds", () => {
1000 if (production) return "deterministic";
1001 if (development) return "named";
1002 return "natural";
1003 });
1004 F(optimization, "sideEffects", () => (production ? true : "flag"));
1005 D(optimization, "providedExports", true);
1006 D(optimization, "usedExports", production);
1007 D(optimization, "innerGraph", production);
1008 D(optimization, "mangleExports", production);
1009 D(optimization, "concatenateModules", production);
1010 D(optimization, "runtimeChunk", false);
1011 D(optimization, "emitOnErrors", !production);
1012 D(optimization, "checkWasmTypes", production);
1013 D(optimization, "mangleWasmImports", false);
1014 D(optimization, "portableRecords", records);
1015 D(optimization, "realContentHash", production);
1016 D(optimization, "minimize", production);
1017 A(optimization, "minimizer", () => [
1018 {
1019 apply: compiler => {
1020 // Lazy load the Terser plugin
1021 const TerserPlugin = require("terser-webpack-plugin");
1022 new TerserPlugin({
1023 terserOptions: {
1024 compress: {
1025 passes: 2
1026 }
1027 }
1028 }).apply(compiler);
1029 }
1030 }
1031 ]);
1032 F(optimization, "nodeEnv", () => {
1033 if (production) return "production";
1034 if (development) return "development";
1035 return false;
1036 });
1037 const { splitChunks } = optimization;
1038 if (splitChunks) {
1039 A(splitChunks, "defaultSizeTypes", () => ["javascript", "unknown"]);
1040 D(splitChunks, "hidePathInfo", production);
1041 D(splitChunks, "chunks", "async");
1042 D(splitChunks, "usedExports", optimization.usedExports === true);
1043 D(splitChunks, "minChunks", 1);
1044 F(splitChunks, "minSize", () => (production ? 20000 : 10000));
1045 F(splitChunks, "minRemainingSize", () => (development ? 0 : undefined));
1046 F(splitChunks, "enforceSizeThreshold", () => (production ? 50000 : 30000));
1047 F(splitChunks, "maxAsyncRequests", () => (production ? 30 : Infinity));
1048 F(splitChunks, "maxInitialRequests", () => (production ? 30 : Infinity));
1049 D(splitChunks, "automaticNameDelimiter", "-");
1050 const { cacheGroups } = splitChunks;
1051 F(cacheGroups, "default", () => ({
1052 idHint: "",
1053 reuseExistingChunk: true,
1054 minChunks: 2,
1055 priority: -20
1056 }));
1057 F(cacheGroups, "defaultVendors", () => ({
1058 idHint: "vendors",
1059 reuseExistingChunk: true,
1060 test: NODE_MODULES_REGEXP,
1061 priority: -10
1062 }));
1063 }
1064};
1065
1066/**
1067 * @param {Object} options options
1068 * @param {boolean} options.cache is cache enable
1069 * @param {string} options.context build context
1070 * @param {TargetProperties | false} options.targetProperties target properties
1071 * @param {Mode} options.mode mode
1072 * @returns {ResolveOptions} resolve options
1073 */
1074const getResolveDefaults = ({ cache, context, targetProperties, mode }) => {
1075 /** @type {string[]} */
1076 const conditions = ["webpack"];
1077
1078 conditions.push(mode === "development" ? "development" : "production");
1079
1080 if (targetProperties) {
1081 if (targetProperties.webworker) conditions.push("worker");
1082 if (targetProperties.node) conditions.push("node");
1083 if (targetProperties.web) conditions.push("browser");
1084 if (targetProperties.electron) conditions.push("electron");
1085 if (targetProperties.nwjs) conditions.push("nwjs");
1086 }
1087
1088 const jsExtensions = [".js", ".json", ".wasm"];
1089
1090 const tp = targetProperties;
1091 const browserField =
1092 tp && tp.web && (!tp.node || (tp.electron && tp.electronRenderer));
1093
1094 /** @type {function(): ResolveOptions} */
1095 const cjsDeps = () => ({
1096 aliasFields: browserField ? ["browser"] : [],
1097 mainFields: browserField ? ["browser", "module", "..."] : ["module", "..."],
1098 conditionNames: ["require", "module", "..."],
1099 extensions: [...jsExtensions]
1100 });
1101 /** @type {function(): ResolveOptions} */
1102 const esmDeps = () => ({
1103 aliasFields: browserField ? ["browser"] : [],
1104 mainFields: browserField ? ["browser", "module", "..."] : ["module", "..."],
1105 conditionNames: ["import", "module", "..."],
1106 extensions: [...jsExtensions]
1107 });
1108
1109 /** @type {ResolveOptions} */
1110 const resolveOptions = {
1111 cache,
1112 modules: ["node_modules"],
1113 conditionNames: conditions,
1114 mainFiles: ["index"],
1115 extensions: [],
1116 aliasFields: [],
1117 exportsFields: ["exports"],
1118 roots: [context],
1119 mainFields: ["main"],
1120 byDependency: {
1121 wasm: esmDeps(),
1122 esm: esmDeps(),
1123 loaderImport: esmDeps(),
1124 url: {
1125 preferRelative: true
1126 },
1127 worker: {
1128 ...esmDeps(),
1129 preferRelative: true
1130 },
1131 commonjs: cjsDeps(),
1132 amd: cjsDeps(),
1133 // for backward-compat: loadModule
1134 loader: cjsDeps(),
1135 // for backward-compat: Custom Dependency
1136 unknown: cjsDeps(),
1137 // for backward-compat: getResolve without dependencyType
1138 undefined: cjsDeps()
1139 }
1140 };
1141
1142 return resolveOptions;
1143};
1144
1145/**
1146 * @param {Object} options options
1147 * @param {boolean} options.cache is cache enable
1148 * @returns {ResolveOptions} resolve options
1149 */
1150const getResolveLoaderDefaults = ({ cache }) => {
1151 /** @type {ResolveOptions} */
1152 const resolveOptions = {
1153 cache,
1154 conditionNames: ["loader", "require", "node"],
1155 exportsFields: ["exports"],
1156 mainFields: ["loader", "main"],
1157 extensions: [".js"],
1158 mainFiles: ["index"]
1159 };
1160
1161 return resolveOptions;
1162};
1163
1164/**
1165 * @param {InfrastructureLogging} infrastructureLogging options
1166 * @returns {void}
1167 */
1168const applyInfrastructureLoggingDefaults = infrastructureLogging => {
1169 F(infrastructureLogging, "stream", () => process.stderr);
1170 const tty =
1171 /** @type {any} */ (infrastructureLogging.stream).isTTY &&
1172 process.env.TERM !== "dumb";
1173 D(infrastructureLogging, "level", "info");
1174 D(infrastructureLogging, "debug", false);
1175 D(infrastructureLogging, "colors", tty);
1176 D(infrastructureLogging, "appendOnly", !tty);
1177};
1178
1179exports.applyWebpackOptionsBaseDefaults = applyWebpackOptionsBaseDefaults;
1180exports.applyWebpackOptionsDefaults = applyWebpackOptionsDefaults;
Note: See TracBrowser for help on using the repository browser.