defaults.js 45 KB

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