defaults.js 48 KB

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