defaults.js 47 KB

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