defaults.js 44 KB

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