defaults.js 48 KB

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