defaults.js 88 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851
  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. CSS_TYPE,
  10. JAVASCRIPT_TYPE,
  11. UNKNOWN_TYPE
  12. } = require("../ModuleSourceTypeConstants");
  13. const {
  14. ASSET_MODULE_TYPE,
  15. ASSET_MODULE_TYPE_BYTES,
  16. ASSET_MODULE_TYPE_INLINE,
  17. ASSET_MODULE_TYPE_RESOURCE,
  18. ASSET_MODULE_TYPE_SOURCE,
  19. CSS_MODULE_TYPE,
  20. CSS_MODULE_TYPE_AUTO,
  21. CSS_MODULE_TYPE_GLOBAL,
  22. CSS_MODULE_TYPE_MODULE,
  23. HTML_MODULE_TYPE,
  24. JAVASCRIPT_MODULE_TYPE_AUTO,
  25. JAVASCRIPT_MODULE_TYPE_DYNAMIC,
  26. JAVASCRIPT_MODULE_TYPE_ESM,
  27. JSON_MODULE_TYPE,
  28. WEBASSEMBLY_MODULE_TYPE_ASYNC,
  29. WEBASSEMBLY_MODULE_TYPE_SYNC
  30. } = require("../ModuleTypeConstants");
  31. const Template = require("../Template");
  32. const RuleSetCompiler = require("../rules/RuleSetCompiler");
  33. const { cleverMerge } = require("../util/cleverMerge");
  34. const {
  35. getDefaultTarget,
  36. getTargetProperties,
  37. getTargetsBrowsers,
  38. getTargetsProperties
  39. } = require("./target");
  40. /**
  41. * @import {
  42. * CacheOptionsNormalized,
  43. * Context,
  44. * DevTool as Devtool,
  45. * CssGeneratorOptions,
  46. * EntryDescription,
  47. * EntryNormalized as Entry,
  48. * Environment,
  49. * Experiments,
  50. * ExperimentsNormalized,
  51. * ExternalsPresets,
  52. * ExternalsType,
  53. * FileCacheOptions,
  54. * GeneratorOptionsByModuleTypeKnown,
  55. * InfrastructureLogging,
  56. * JavascriptParserOptions,
  57. * JsonGeneratorOptions,
  58. * Library,
  59. * LibraryName,
  60. * LibraryType,
  61. * Loader,
  62. * Mode,
  63. * HashFunction,
  64. * HashSalt,
  65. * ModuleOptionsNormalized as ModuleOptions,
  66. * Node as WebpackNode,
  67. * OptimizationMinimizeOptions,
  68. * OptimizationNormalized as Optimization,
  69. * OptimizationSplitChunksOptions,
  70. * OutputNormalized as Output,
  71. * ParserOptionsByModuleTypeKnown,
  72. * Performance,
  73. * ResolveOptions,
  74. * RuleSetRules,
  75. * SnapshotOptions,
  76. * WebpackOptionsNormalized
  77. * } from "../../declarations/WebpackOptions"
  78. */
  79. /** @import Module from "../Module" */
  80. /**
  81. * @import {
  82. * ChunkLoadingTypes
  83. * } from "../javascript/EnableChunkLoadingPlugin"
  84. */
  85. /** @import { WasmLoadingTypes } from "../wasm/EnableWasmLoadingPlugin" */
  86. /** @import { PlatformTargetProperties, TargetProperties } from "./target" */
  87. /**
  88. * Defines the recursive non nullable type used by this module.
  89. * @template T
  90. * @typedef {{ [P in keyof T]-?: T[P] extends object ? RecursiveNonNullable<NonNullable<T[P]>> : NonNullable<T[P]> }} RecursiveNonNullable
  91. */
  92. /**
  93. * Defines the shared type used by this module.
  94. * @typedef {Output & {
  95. * uniqueName: NonNullable<Output["uniqueName"]>,
  96. * filename: NonNullable<Output["filename"]>,
  97. * cssFilename: NonNullable<Output["cssFilename"]>,
  98. * chunkFilename: NonNullable<Output["chunkFilename"]>,
  99. * cssChunkFilename: NonNullable<Output["cssChunkFilename"]>,
  100. * hotUpdateChunkFilename: NonNullable<Output["hotUpdateChunkFilename"]>,
  101. * hotUpdateGlobal: NonNullable<Output["hotUpdateGlobal"]>,
  102. * assetModuleFilename: NonNullable<Output["assetModuleFilename"]>,
  103. * webassemblyModuleFilename: NonNullable<Output["webassemblyModuleFilename"]>,
  104. * sourceMapFilename: NonNullable<Output["sourceMapFilename"]>,
  105. * hotUpdateMainFilename: NonNullable<Output["hotUpdateMainFilename"]>,
  106. * devtoolNamespace: NonNullable<Output["devtoolNamespace"]>,
  107. * publicPath: NonNullable<Output["publicPath"]>,
  108. * workerPublicPath: NonNullable<Output["workerPublicPath"]>,
  109. * workerChunkFilename: NonNullable<Output["workerChunkFilename"]>,
  110. * workerWasmLoading: NonNullable<Output["workerWasmLoading"]>,
  111. * workerChunkLoading: NonNullable<Output["workerChunkLoading"]>,
  112. * chunkFormat: NonNullable<Output["chunkFormat"]>,
  113. * module: NonNullable<Output["module"]>,
  114. * asyncChunks: NonNullable<Output["asyncChunks"]>,
  115. * charset: NonNullable<Output["charset"]>,
  116. * iife: NonNullable<Output["iife"]>,
  117. * globalObject: NonNullable<Output["globalObject"]>,
  118. * scriptType: NonNullable<Output["scriptType"]>,
  119. * path: NonNullable<Output["path"]>,
  120. * pathinfo: NonNullable<Output["pathinfo"]>,
  121. * hashFunction: NonNullable<Output["hashFunction"]>,
  122. * hashDigest: NonNullable<Output["hashDigest"]>,
  123. * hashDigestLength: NonNullable<Output["hashDigestLength"]>,
  124. * chunkLoadTimeout: NonNullable<Output["chunkLoadTimeout"]>,
  125. * chunkLoading: NonNullable<Output["chunkLoading"]>,
  126. * chunkLoadingGlobal: NonNullable<Output["chunkLoadingGlobal"]>,
  127. * compareBeforeEmit: NonNullable<Output["compareBeforeEmit"]>,
  128. * strictModuleErrorHandling: NonNullable<Output["strictModuleErrorHandling"]>,
  129. * strictModuleExceptionHandling: NonNullable<Output["strictModuleExceptionHandling"]>,
  130. * strictModuleResolution: NonNullable<Output["strictModuleResolution"]>,
  131. * importFunctionName: NonNullable<Output["importFunctionName"]>,
  132. * importMetaName: NonNullable<Output["importMetaName"]>,
  133. * environment: RecursiveNonNullable<Output["environment"]>,
  134. * crossOriginLoading: NonNullable<Output["crossOriginLoading"]>,
  135. * wasmLoading: NonNullable<Output["wasmLoading"]>,
  136. * }} OutputNormalizedWithDefaults
  137. */
  138. /**
  139. * Defines the shared type used by this module.
  140. * @typedef {SnapshotOptions & {
  141. * managedPaths: NonNullable<SnapshotOptions["managedPaths"]>,
  142. * unmanagedPaths: NonNullable<SnapshotOptions["unmanagedPaths"]>,
  143. * immutablePaths: NonNullable<SnapshotOptions["immutablePaths"]>,
  144. * resolveBuildDependencies: NonNullable<SnapshotOptions["resolveBuildDependencies"]>,
  145. * buildDependencies: NonNullable<SnapshotOptions["buildDependencies"]>,
  146. * module: NonNullable<SnapshotOptions["module"]>,
  147. * resolve: NonNullable<SnapshotOptions["resolve"]>,
  148. * }} SnapshotNormalizedWithDefaults
  149. */
  150. /**
  151. * Defines the shared type used by this module.
  152. * @typedef {Optimization & {
  153. * runtimeChunk: NonNullable<Optimization["runtimeChunk"]>,
  154. * splitChunks: NonNullable<Optimization["splitChunks"]>,
  155. * mergeDuplicateChunks: NonNullable<Optimization["mergeDuplicateChunks"]>,
  156. * removeAvailableModules: NonNullable<Optimization["removeAvailableModules"]>,
  157. * removeEmptyChunks: NonNullable<Optimization["removeEmptyChunks"]>,
  158. * flagIncludedChunks: NonNullable<Optimization["flagIncludedChunks"]>,
  159. * moduleIds: NonNullable<Optimization["moduleIds"]>,
  160. * chunkIds: NonNullable<Optimization["chunkIds"]>,
  161. * sideEffects: NonNullable<Optimization["sideEffects"]>,
  162. * providedExports: NonNullable<Optimization["providedExports"]>,
  163. * usedExports: NonNullable<Optimization["usedExports"]>,
  164. * mangleExports: NonNullable<Optimization["mangleExports"]>,
  165. * innerGraph: NonNullable<Optimization["innerGraph"]>,
  166. * inlineExports: NonNullable<Optimization["inlineExports"]>,
  167. * concatenateModules: NonNullable<Optimization["concatenateModules"]>,
  168. * avoidEntryIife: NonNullable<Optimization["avoidEntryIife"]>,
  169. * emitOnErrors: NonNullable<Optimization["emitOnErrors"]>,
  170. * checkWasmTypes: NonNullable<Optimization["checkWasmTypes"]>,
  171. * mangleWasmImports: NonNullable<Optimization["mangleWasmImports"]>,
  172. * portableRecords: NonNullable<Optimization["portableRecords"]>,
  173. * realContentHash: NonNullable<Optimization["realContentHash"]>,
  174. * minimize: NonNullable<Optimization["minimize"]>,
  175. * minimizer: NonNullable<Exclude<Optimization["minimizer"], "...">>,
  176. * nodeEnv: NonNullable<Optimization["nodeEnv"]>,
  177. * }} OptimizationNormalizedWithDefaults
  178. */
  179. /**
  180. * Defines the shared type used by this module.
  181. * @typedef {ExternalsPresets & {
  182. * web: NonNullable<ExternalsPresets["web"]>,
  183. * node: NonNullable<ExternalsPresets["node"]>,
  184. * nwjs: NonNullable<ExternalsPresets["nwjs"]>,
  185. * electron: NonNullable<ExternalsPresets["electron"]>,
  186. * electronMain: NonNullable<ExternalsPresets["electronMain"]>,
  187. * electronPreload: NonNullable<ExternalsPresets["electronPreload"]>,
  188. * electronRenderer: NonNullable<ExternalsPresets["electronRenderer"]>,
  189. * }} ExternalsPresetsNormalizedWithDefaults
  190. */
  191. /**
  192. * Defines the shared type used by this module.
  193. * @typedef {InfrastructureLogging & {
  194. * stream: NonNullable<InfrastructureLogging["stream"]>,
  195. * level: NonNullable<InfrastructureLogging["level"]>,
  196. * debug: NonNullable<InfrastructureLogging["debug"]>,
  197. * colors: NonNullable<InfrastructureLogging["colors"]>,
  198. * appendOnly: NonNullable<InfrastructureLogging["appendOnly"]>,
  199. * }} InfrastructureLoggingNormalizedWithDefaults
  200. */
  201. /**
  202. * Defines the webpack options normalized with base defaults type used by this module.
  203. * @typedef {WebpackOptionsNormalized & { context: NonNullable<WebpackOptionsNormalized["context"]> } & { infrastructureLogging: InfrastructureLoggingNormalizedWithDefaults }} WebpackOptionsNormalizedWithBaseDefaults
  204. */
  205. /**
  206. * Defines the webpack options normalized with defaults type used by this module.
  207. * @typedef {WebpackOptionsNormalizedWithBaseDefaults & { target: NonNullable<WebpackOptionsNormalized["target"]> } & { output: OutputNormalizedWithDefaults } & { optimization: OptimizationNormalizedWithDefaults } & { devtool: NonNullable<WebpackOptionsNormalized["devtool"]> } & { stats: NonNullable<WebpackOptionsNormalized["stats"]> } & { node: NonNullable<WebpackOptionsNormalized["node"]> } & { profile: NonNullable<WebpackOptionsNormalized["profile"]> } & { parallelism: NonNullable<WebpackOptionsNormalized["parallelism"]> } & { snapshot: SnapshotNormalizedWithDefaults } & { externalsPresets: ExternalsPresetsNormalizedWithDefaults } & { externalsType: NonNullable<WebpackOptionsNormalized["externalsType"]> } & { watch: NonNullable<WebpackOptionsNormalized["watch"]> } & { performance: NonNullable<WebpackOptionsNormalized["performance"]> } & { recordsInputPath: NonNullable<WebpackOptionsNormalized["recordsInputPath"]> } & { recordsOutputPath: NonNullable<WebpackOptionsNormalized["recordsOutputPath"]> } & { dotenv: NonNullable<WebpackOptionsNormalized["dotenv"]> }} WebpackOptionsNormalizedWithDefaults
  208. */
  209. /**
  210. * Defines the resolved options type used by this module.
  211. * @typedef {object} ResolvedOptions
  212. * @property {PlatformTargetProperties | false} platform - platform target properties
  213. */
  214. const NODE_MODULES_REGEXP = /[\\/]node_modules[\\/]/i;
  215. const DEFAULT_CACHE_NAME = "default";
  216. const DEFAULTS = {
  217. // TODO webpack 6 - use xxhash64
  218. HASH_FUNCTION: "md4"
  219. };
  220. /**
  221. * Processes the provided obj.
  222. * @template T
  223. * @template {keyof T} P
  224. * @param {T} obj an object
  225. * @param {P} prop a property of this object
  226. * @param {T[P]} value a default value of the property
  227. * @returns {void}
  228. */
  229. const D = (obj, prop, value) => {
  230. if (obj[prop] === undefined) {
  231. obj[prop] = value;
  232. }
  233. };
  234. /**
  235. * Processes the provided obj.
  236. * @template T
  237. * @template {keyof T} P
  238. * @param {T} obj an object
  239. * @param {P} prop a property of this object
  240. * @param {() => T[P]} factory a default value factory for the property
  241. * @returns {void}
  242. */
  243. const F = (obj, prop, factory) => {
  244. if (obj[prop] === undefined) {
  245. obj[prop] = factory();
  246. }
  247. };
  248. /**
  249. * Sets a dynamic default value when undefined, by calling the factory function.
  250. * factory must return an array or undefined
  251. * When the current value is already an array an contains "..." it's replaced with
  252. * the result of the factory function
  253. * @template T
  254. * @template {keyof T} P
  255. * @param {T} obj an object
  256. * @param {P} prop a property of this object
  257. * @param {() => T[P]} factory a default value factory for the property
  258. * @returns {void}
  259. */
  260. const A = (obj, prop, factory) => {
  261. const value = obj[prop];
  262. if (value === undefined) {
  263. obj[prop] = factory();
  264. } else if (Array.isArray(value)) {
  265. /** @type {EXPECTED_ANY[] | undefined} */
  266. let newArray;
  267. for (let i = 0; i < value.length; i++) {
  268. const item = value[i];
  269. if (item === "...") {
  270. if (newArray === undefined) {
  271. newArray = value.slice(0, i);
  272. obj[prop] = /** @type {T[P]} */ (/** @type {unknown} */ (newArray));
  273. }
  274. const items =
  275. /** @type {EXPECTED_ANY[]} */
  276. (/** @type {unknown} */ (factory()));
  277. if (items !== undefined) {
  278. for (const item of items) {
  279. newArray.push(item);
  280. }
  281. }
  282. } else if (newArray !== undefined) {
  283. newArray.push(item);
  284. }
  285. }
  286. }
  287. };
  288. /**
  289. * Apply webpack options base defaults.
  290. * @param {WebpackOptionsNormalized} options options to be modified
  291. * @returns {void}
  292. */
  293. const applyWebpackOptionsBaseDefaults = (options) => {
  294. F(options, "context", () => process.cwd());
  295. applyInfrastructureLoggingDefaults(options.infrastructureLogging);
  296. };
  297. /**
  298. * Apply webpack options defaults.
  299. * @param {WebpackOptionsNormalized} options options to be modified
  300. * @param {number=} compilerIndex index of compiler
  301. * @returns {ResolvedOptions} Resolved options after apply defaults
  302. */
  303. const applyWebpackOptionsDefaults = (options, compilerIndex) => {
  304. F(options, "context", () => process.cwd());
  305. F(options, "target", () =>
  306. getDefaultTarget(/** @type {string} */ (options.context))
  307. );
  308. const { mode, name, target } = options;
  309. const targetProperties =
  310. target === false
  311. ? /** @type {false} */ (false)
  312. : typeof target === "string"
  313. ? getTargetProperties(target, /** @type {Context} */ (options.context))
  314. : getTargetsProperties(
  315. /** @type {string[]} */ (target),
  316. /** @type {Context} */ (options.context)
  317. );
  318. const development = mode === "development";
  319. const production = mode === "production" || !mode;
  320. if (typeof options.entry !== "function") {
  321. for (const key of Object.keys(options.entry)) {
  322. F(
  323. options.entry[key],
  324. "import",
  325. () => /** @type {[string]} */ (["./src"])
  326. );
  327. }
  328. }
  329. D(options, "watch", false);
  330. D(options, "profile", false);
  331. D(options, "parallelism", 100);
  332. D(options, "recordsInputPath", false);
  333. D(options, "recordsOutputPath", false);
  334. // Capture the raw html intent before "auto" is resolved: only an explicit
  335. // `html: true` (or futureDefaults) keeps `.html` ahead of `.js` when resolving.
  336. const htmlExplicitlyEnabled = options.experiments.html === true;
  337. const htmlWasUnset = options.experiments.html === undefined;
  338. applyExperimentsDefaults(options.experiments, {
  339. production,
  340. development,
  341. targetProperties,
  342. rules: options.module.rules
  343. });
  344. const futureDefaults =
  345. /** @type {NonNullable<ExperimentsNormalized["futureDefaults"]>} */
  346. (options.experiments.futureDefaults);
  347. // `.html` outranks `.js` only for an explicit opt-in (`html: true`, or the
  348. // futureDefaults-forced default), never for the auto-enabled default.
  349. const htmlFirst = htmlExplicitlyEnabled || (htmlWasUnset && futureDefaults);
  350. F(options, "validate", () => !(futureDefaults === true && production));
  351. // Progress lives on infrastructureLogging; webpack@6 shows the interactive
  352. // bar by default (`"auto"` = TTY only), webpack@5 stays opt-in.
  353. D(options.infrastructureLogging, "progress", futureDefaults ? "auto" : false);
  354. F(options, "cache", () =>
  355. development ? { type: /** @type {"memory"} */ ("memory") } : false
  356. );
  357. applyCacheDefaults(options.cache, {
  358. name: name || DEFAULT_CACHE_NAME,
  359. mode: mode || "production",
  360. development,
  361. cacheUnaffected: options.experiments.cacheUnaffected,
  362. futureDefaults,
  363. compilerIndex
  364. });
  365. const cache = Boolean(options.cache);
  366. applySnapshotDefaults(options.snapshot, {
  367. production,
  368. futureDefaults
  369. });
  370. applyOutputDefaults(options.output, {
  371. context: /** @type {Context} */ (options.context),
  372. targetProperties,
  373. isAffectedByBrowserslist:
  374. target === undefined ||
  375. (typeof target === "string" && target.startsWith("browserslist")) ||
  376. (Array.isArray(target) &&
  377. target.some((target) => target.startsWith("browserslist"))),
  378. outputModule:
  379. /** @type {NonNullable<ExperimentsNormalized["outputModule"]>} */
  380. (options.experiments.outputModule),
  381. development,
  382. entry: options.entry,
  383. futureDefaults,
  384. asyncWebAssembly:
  385. /** @type {boolean} */
  386. (options.experiments.asyncWebAssembly)
  387. });
  388. // Placed after `applyOutputDefaults`, which settles `enabledLibraryTypes`. A library
  389. // is read by another bundler, where an eval wrapper hides `import.meta` from it.
  390. const noDevSourceMap = /** @type {LibraryType[]} */ (
  391. options.output.enabledLibraryTypes
  392. ).some(
  393. (type) => futureDefaults || type === "module" || type === "modern-module"
  394. );
  395. F(
  396. options,
  397. "devtool",
  398. () =>
  399. /** @type {Devtool} */ (
  400. development && !noDevSourceMap
  401. ? [
  402. options.experiments.css
  403. ? {
  404. type: "css",
  405. use: "source-map"
  406. }
  407. : undefined,
  408. {
  409. type: "javascript",
  410. use: "eval"
  411. }
  412. ].filter(Boolean)
  413. : false
  414. )
  415. );
  416. applyModuleDefaults(options.module, {
  417. cache,
  418. hashSalt: /** @type {NonNullable<Output["hashSalt"]>} */ (
  419. options.output.hashSalt
  420. ),
  421. hashFunction: /** @type {NonNullable<Output["hashFunction"]>} */ (
  422. options.output.hashFunction
  423. ),
  424. syncWebAssembly:
  425. /** @type {NonNullable<ExperimentsNormalized["syncWebAssembly"]>} */
  426. (options.experiments.syncWebAssembly),
  427. asyncWebAssembly:
  428. /** @type {boolean} */
  429. (options.experiments.asyncWebAssembly),
  430. css:
  431. /** @type {boolean} */
  432. (options.experiments.css),
  433. html:
  434. /** @type {boolean} */
  435. (options.experiments.html),
  436. typescript:
  437. /** @type {boolean} */
  438. (options.experiments.typescript),
  439. deferImport:
  440. /** @type {NonNullable<ExperimentsNormalized["deferImport"]>} */
  441. (options.experiments.deferImport),
  442. sourceImport:
  443. /** @type {NonNullable<ExperimentsNormalized["sourceImport"]>} */
  444. (options.experiments.sourceImport),
  445. futureDefaults,
  446. isNode: targetProperties && targetProperties.node === true,
  447. uniqueName: /** @type {string} */ (options.output.uniqueName),
  448. targetProperties,
  449. mode: options.mode,
  450. outputModule:
  451. /** @type {NonNullable<WebpackOptionsNormalized["output"]["module"]>} */
  452. (options.output.module),
  453. library: options.output.library
  454. });
  455. // `output.resourceHints.urlHints` shorthand: fan the project-wide rules out
  456. // as the base `urlHints` of every URL-emitting parser (JS `new URL`, CSS
  457. // `url()`, HTML `<img src>`). They go first so parser-scoped
  458. // `parser.<type>.urlHints` rules — matched later, last-match-wins — override.
  459. const outputUrlHints =
  460. options.output.resourceHints && options.output.resourceHints.urlHints;
  461. if (outputUrlHints && outputUrlHints.length > 0) {
  462. for (const type of [
  463. "javascript",
  464. CSS_MODULE_TYPE,
  465. CSS_MODULE_TYPE_AUTO,
  466. CSS_MODULE_TYPE_MODULE,
  467. CSS_MODULE_TYPE_GLOBAL,
  468. HTML_MODULE_TYPE
  469. ]) {
  470. const parser =
  471. /** @type {{ urlHints?: import("../../declarations/WebpackOptions").UrlHintRule[] } | undefined} */
  472. (options.module.parser[type]);
  473. if (!parser) continue;
  474. parser.urlHints = [...outputUrlHints, ...(parser.urlHints || [])];
  475. }
  476. }
  477. applyExternalsPresetsDefaults(options.externalsPresets, {
  478. targetProperties,
  479. buildHttp: Boolean(options.experiments.buildHttp),
  480. outputModule:
  481. /** @type {NonNullable<WebpackOptionsNormalized["output"]["module"]>} */
  482. (options.output.module)
  483. });
  484. applyLoaderDefaults(
  485. /** @type {NonNullable<WebpackOptionsNormalized["loader"]>} */ (
  486. options.loader
  487. ),
  488. {
  489. targetProperties,
  490. environment: options.output.environment,
  491. outputModule:
  492. /** @type {NonNullable<WebpackOptionsNormalized["output"]["module"]>} */
  493. (options.output.module)
  494. }
  495. );
  496. F(options, "externalsType", () => {
  497. const validExternalTypes = require("../../schemas/WebpackOptions.json")
  498. .definitions.ExternalsType.enum;
  499. return options.output.library &&
  500. validExternalTypes.includes(options.output.library.type)
  501. ? /** @type {ExternalsType} */ (options.output.library.type)
  502. : options.output.module
  503. ? "module-import"
  504. : "var";
  505. });
  506. applyNodeDefaults(options.node, {
  507. futureDefaults:
  508. /** @type {NonNullable<WebpackOptionsNormalized["experiments"]["futureDefaults"]>} */
  509. (options.experiments.futureDefaults),
  510. outputModule:
  511. /** @type {NonNullable<WebpackOptionsNormalized["output"]["module"]>} */
  512. (options.output.module),
  513. targetProperties
  514. });
  515. F(options, "performance", () =>
  516. production &&
  517. targetProperties &&
  518. (targetProperties.browser || targetProperties.browser === null)
  519. ? {}
  520. : false
  521. );
  522. applyPerformanceDefaults(
  523. /** @type {NonNullable<WebpackOptionsNormalized["performance"]>} */
  524. (options.performance),
  525. {
  526. production
  527. }
  528. );
  529. applyOptimizationDefaults(options.optimization, {
  530. development,
  531. production,
  532. css:
  533. /** @type {boolean} */
  534. (options.experiments.css),
  535. records: Boolean(options.recordsInputPath || options.recordsOutputPath)
  536. });
  537. options.resolve = cleverMerge(
  538. getResolveDefaults({
  539. cache,
  540. context: /** @type {Context} */ (options.context),
  541. targetProperties,
  542. mode: /** @type {Mode} */ (options.mode),
  543. css:
  544. /** @type {boolean} */
  545. (options.experiments.css),
  546. html:
  547. /** @type {boolean} */
  548. (options.experiments.html),
  549. htmlFirst,
  550. typescript:
  551. /** @type {boolean} */
  552. (options.experiments.typescript)
  553. }),
  554. options.resolve
  555. );
  556. options.resolveLoader = cleverMerge(
  557. getResolveLoaderDefaults({ cache }),
  558. options.resolveLoader
  559. );
  560. return {
  561. platform:
  562. targetProperties === false
  563. ? targetProperties
  564. : {
  565. web: targetProperties.web,
  566. browser: targetProperties.browser,
  567. webworker: targetProperties.webworker,
  568. node: targetProperties.node,
  569. deno: targetProperties.deno,
  570. bun: targetProperties.bun,
  571. nwjs: targetProperties.nwjs,
  572. electron: targetProperties.electron,
  573. // spans both web and node (target "universal" or ["web", "node"])
  574. universal:
  575. targetProperties.node === null && targetProperties.web === null
  576. }
  577. };
  578. };
  579. /**
  580. * Apply experiments defaults.
  581. * @param {ExperimentsNormalized} experiments options
  582. * @param {object} options options
  583. * @param {boolean} options.production is production
  584. * @param {boolean} options.development is development mode
  585. * @param {TargetProperties | false} options.targetProperties target properties
  586. * @param {RuleSetRules} options.rules user `module.rules`, used to resolve the css/html/asyncWebAssembly/typescript "auto" defaults
  587. * @returns {void}
  588. */
  589. const applyExperimentsDefaults = (
  590. experiments,
  591. { production, development, targetProperties, rules }
  592. ) => {
  593. D(experiments, "futureDefaults", false);
  594. D(experiments, "backCompat", !experiments.futureDefaults);
  595. // TODO do we need sync web assembly in webpack@6?
  596. D(experiments, "syncWebAssembly", false);
  597. D(
  598. experiments,
  599. "asyncWebAssembly",
  600. experiments.futureDefaults ? true : "auto"
  601. );
  602. // the universal target (web + node, neither specific) only works as ESM —
  603. // unless the target cannot read one, which no output format can repair, so
  604. // leave `output.chunkFormat` to say so rather than emitting a module the
  605. // target has already reported it will not load
  606. const universal =
  607. Boolean(targetProperties) &&
  608. /** @type {TargetProperties} */ (targetProperties).node === null &&
  609. /** @type {TargetProperties} */ (targetProperties).web === null &&
  610. /** @type {TargetProperties} */ (targetProperties).module !== false;
  611. // the deno and bun targets only emit ECMAScript modules
  612. const deno =
  613. Boolean(targetProperties) &&
  614. /** @type {TargetProperties} */ (targetProperties).deno === true;
  615. const bun =
  616. Boolean(targetProperties) &&
  617. /** @type {TargetProperties} */ (targetProperties).bun === true;
  618. D(experiments, "outputModule", universal || deno || bun);
  619. D(experiments, "lazyCompilation", undefined);
  620. D(experiments, "buildHttp", undefined);
  621. D(experiments, "cacheUnaffected", experiments.futureDefaults);
  622. D(experiments, "deferImport", false);
  623. D(experiments, "sourceImport", false);
  624. F(experiments, "css", () => (experiments.futureDefaults ? true : "auto"));
  625. F(experiments, "html", () => (experiments.futureDefaults ? true : "auto"));
  626. F(experiments, "typescript", () =>
  627. experiments.futureDefaults ? true : "auto"
  628. );
  629. // Resolve the "auto" default: enable the built-in css/html module type unless
  630. // the user already registered a loader (or explicit type) for these files, so
  631. // enabling them by default does not break existing css-loader/html-loader setups.
  632. // The built-in `/\.css$/i` rule also covers `.module.css`, so a loader scoped to
  633. // CSS modules must disable the built-in type too — sample both extensions.
  634. // When enabled implicitly the value stays `"auto"` (truthy): Css/HtmlModulesPlugin
  635. // then step aside per-module for requests that loaders were applied to
  636. // (inline requests or loaders injected via hooks, e.g. html-webpack-plugin).
  637. // TODO webpack 6: css/html default to `true`, drop the `"auto"` marker.
  638. if (experiments.css === "auto") {
  639. experiments.css =
  640. !(
  641. RuleSetCompiler.hasRuleForResource(rules, "/file.css") ||
  642. RuleSetCompiler.hasRuleForResource(rules, "/file.module.css")
  643. ) && "auto";
  644. }
  645. if (experiments.html === "auto") {
  646. experiments.html =
  647. !RuleSetCompiler.hasRuleForResource(rules, "/file.html") && "auto";
  648. }
  649. // Auto-enable only when the built-in TypeScript support can actually run:
  650. // it needs `module.stripTypeScriptTypes` (Node.js >= 22.6) and must step
  651. // aside for a loader registered for `.ts`/`.mts`/`.cts` (e.g. ts-loader).
  652. if (experiments.typescript === "auto") {
  653. experiments.typescript =
  654. // eslint-disable-next-line n/no-unsupported-features/node-builtins
  655. typeof require("module").stripTypeScriptTypes === "function" &&
  656. !(
  657. RuleSetCompiler.hasRuleForResource(rules, "/file.ts") ||
  658. RuleSetCompiler.hasRuleForResource(rules, "/file.mts") ||
  659. RuleSetCompiler.hasRuleForResource(rules, "/file.cts")
  660. );
  661. }
  662. // `syncWebAssembly` already claims `.wasm`, so don't let "auto" override it.
  663. if (experiments.asyncWebAssembly === "auto") {
  664. experiments.asyncWebAssembly =
  665. !experiments.syncWebAssembly &&
  666. !RuleSetCompiler.hasRuleForResource(rules, "/file.wasm");
  667. }
  668. if (typeof experiments.buildHttp === "object") {
  669. D(experiments.buildHttp, "frozen", production);
  670. D(experiments.buildHttp, "upgrade", false);
  671. }
  672. };
  673. /**
  674. * Apply cache defaults.
  675. * @param {CacheOptionsNormalized} cache options
  676. * @param {object} options options
  677. * @param {string} options.name name
  678. * @param {Mode} options.mode mode
  679. * @param {boolean} options.futureDefaults is future defaults enabled
  680. * @param {boolean} options.development is development mode
  681. * @param {number=} options.compilerIndex index of compiler
  682. * @param {Experiments["cacheUnaffected"]} options.cacheUnaffected the cacheUnaffected experiment is enabled
  683. * @returns {void}
  684. */
  685. const applyCacheDefaults = (
  686. cache,
  687. { name, mode, development, cacheUnaffected, compilerIndex, futureDefaults }
  688. ) => {
  689. if (cache === false) return;
  690. switch (cache.type) {
  691. case "filesystem":
  692. F(cache, "name", () =>
  693. compilerIndex !== undefined
  694. ? `${`${name}-${mode}`}__compiler${compilerIndex + 1}__`
  695. : `${name}-${mode}`
  696. );
  697. D(cache, "version", "");
  698. F(cache, "cacheDirectory", () => {
  699. const cwd = process.cwd();
  700. /** @type {string | undefined} */
  701. let dir = cwd;
  702. for (;;) {
  703. try {
  704. if (fs.statSync(path.join(dir, "package.json")).isFile()) break;
  705. // eslint-disable-next-line no-empty
  706. } catch (_err) {}
  707. const parent = path.dirname(dir);
  708. if (dir === parent) {
  709. dir = undefined;
  710. break;
  711. }
  712. dir = parent;
  713. }
  714. if (!dir) {
  715. return path.resolve(cwd, ".cache/webpack");
  716. } else if (process.versions.pnp === "1") {
  717. return path.resolve(dir, ".pnp/.cache/webpack");
  718. } else if (process.versions.pnp === "3") {
  719. return path.resolve(dir, ".yarn/.cache/webpack");
  720. }
  721. return path.resolve(dir, "node_modules/.cache/webpack");
  722. });
  723. F(cache, "cacheLocation", () =>
  724. path.resolve(
  725. /** @type {NonNullable<FileCacheOptions["cacheDirectory"]>} */
  726. (cache.cacheDirectory),
  727. /** @type {NonNullable<FileCacheOptions["name"]>} */ (cache.name)
  728. )
  729. );
  730. D(cache, "hashAlgorithm", futureDefaults ? "xxhash64" : "md4");
  731. D(cache, "store", "pack");
  732. D(cache, "compression", false);
  733. D(cache, "profile", false);
  734. D(cache, "idleTimeout", 60000);
  735. D(cache, "idleTimeoutForInitialStore", 5000);
  736. D(cache, "idleTimeoutAfterLargeChanges", 1000);
  737. D(cache, "maxMemoryGenerations", development ? 5 : Infinity);
  738. D(cache, "maxAge", 1000 * 60 * 60 * 24 * 60); // 1 month
  739. D(cache, "allowCollectingMemory", development);
  740. D(cache, "memoryCacheUnaffected", development && cacheUnaffected);
  741. D(cache, "readonly", false);
  742. D(
  743. /** @type {NonNullable<FileCacheOptions["buildDependencies"]>} */
  744. (cache.buildDependencies),
  745. "defaultWebpack",
  746. [path.resolve(__dirname, "..") + path.sep]
  747. );
  748. break;
  749. case "memory":
  750. D(cache, "maxGenerations", Infinity);
  751. D(cache, "cacheUnaffected", development && cacheUnaffected);
  752. break;
  753. }
  754. };
  755. /**
  756. * Apply snapshot defaults.
  757. * @param {SnapshotOptions} snapshot options
  758. * @param {object} options options
  759. * @param {boolean} options.production is production
  760. * @param {boolean} options.futureDefaults is future defaults enabled
  761. * @returns {void}
  762. */
  763. const applySnapshotDefaults = (snapshot, { production, futureDefaults }) => {
  764. if (futureDefaults) {
  765. F(snapshot, "managedPaths", () =>
  766. process.versions.pnp === "3"
  767. ? [
  768. /^(.+?(?:[\\/]\.yarn[\\/]unplugged[\\/][^\\/]+)?[\\/]node_modules[\\/])/
  769. ]
  770. : [/^(.+?[\\/]node_modules[\\/])/]
  771. );
  772. F(snapshot, "immutablePaths", () =>
  773. process.versions.pnp === "3"
  774. ? [/^(.+?[\\/]cache[\\/][^\\/]+\.zip[\\/]node_modules[\\/])/]
  775. : []
  776. );
  777. } else {
  778. A(snapshot, "managedPaths", () => {
  779. if (process.versions.pnp === "3") {
  780. const match =
  781. /^(.+?)[\\/]cache[\\/]watchpack-npm-[^\\/]+\.zip[\\/]node_modules[\\/]/.exec(
  782. require.resolve("watchpack")
  783. );
  784. if (match) {
  785. return [path.resolve(match[1], "unplugged")];
  786. }
  787. } else {
  788. const match = /^(.+?[\\/]node_modules[\\/])/.exec(
  789. require.resolve("watchpack")
  790. );
  791. if (match) {
  792. return [match[1]];
  793. }
  794. }
  795. return [];
  796. });
  797. A(snapshot, "immutablePaths", () => {
  798. if (process.versions.pnp === "1") {
  799. const match =
  800. /^(.+?[\\/]v4)[\\/]npm-watchpack-[^\\/]+-[\da-f]{40}[\\/]node_modules[\\/]/.exec(
  801. require.resolve("watchpack")
  802. );
  803. if (match) {
  804. return [match[1]];
  805. }
  806. } else if (process.versions.pnp === "3") {
  807. const match =
  808. /^(.+?)[\\/]watchpack-npm-[^\\/]+\.zip[\\/]node_modules[\\/]/.exec(
  809. require.resolve("watchpack")
  810. );
  811. if (match) {
  812. return [match[1]];
  813. }
  814. }
  815. return [];
  816. });
  817. }
  818. F(snapshot, "unmanagedPaths", () => []);
  819. F(snapshot, "resolveBuildDependencies", () => ({
  820. timestamp: true,
  821. hash: true
  822. }));
  823. F(snapshot, "buildDependencies", () => ({ timestamp: true, hash: true }));
  824. F(snapshot, "module", () =>
  825. production ? { timestamp: true, hash: true } : { timestamp: true }
  826. );
  827. F(snapshot, "contextModule", () => ({ timestamp: true }));
  828. F(snapshot, "resolve", () =>
  829. production ? { timestamp: true, hash: true } : { timestamp: true }
  830. );
  831. };
  832. /**
  833. * Apply javascript parser options defaults.
  834. * @param {JavascriptParserOptions} parserOptions parser options
  835. * @param {object} options options
  836. * @param {boolean} options.futureDefaults is future defaults enabled
  837. * @param {boolean} options.deferImport is defer import enabled
  838. * @param {boolean} options.sourceImport is import source enabled
  839. * @param {boolean} options.isNode is node target platform
  840. * @param {boolean} options.outputModule is output.module enabled
  841. * @param {WebpackOptionsNormalized["output"]["library"]} options.library library options
  842. * @param {boolean} options.typescript is typescript enabled
  843. * @returns {void}
  844. */
  845. const applyJavascriptParserOptionsDefaults = (
  846. parserOptions,
  847. {
  848. futureDefaults,
  849. deferImport,
  850. sourceImport,
  851. isNode,
  852. outputModule,
  853. library,
  854. typescript
  855. }
  856. ) => {
  857. D(parserOptions, "unknownContextRequest", ".");
  858. D(parserOptions, "unknownContextRegExp", false);
  859. D(parserOptions, "unknownContextRecursive", true);
  860. D(parserOptions, "unknownContextCritical", true);
  861. D(parserOptions, "exprContextRequest", ".");
  862. D(parserOptions, "exprContextRegExp", false);
  863. D(parserOptions, "exprContextRecursive", true);
  864. D(parserOptions, "exprContextCritical", true);
  865. D(parserOptions, "wrappedContextRegExp", /.*/);
  866. D(parserOptions, "wrappedContextRecursive", true);
  867. D(parserOptions, "wrappedContextCritical", false);
  868. D(parserOptions, "strictThisContextOnImports", false);
  869. D(parserOptions, "importMeta", outputModule ? "preserve-unknown" : true);
  870. D(parserOptions, "dynamicImportMode", "lazy");
  871. D(parserOptions, "dynamicImportPrefetch", false);
  872. D(parserOptions, "dynamicImportPreload", false);
  873. D(parserOptions, "dynamicImportFetchPriority", false);
  874. D(parserOptions, "createRequire", isNode);
  875. D(parserOptions, "dynamicUrl", true);
  876. D(parserOptions, "deferImport", deferImport);
  877. D(parserOptions, "sourceImport", sourceImport);
  878. D(parserOptions, "typescript", typescript);
  879. if (futureDefaults) D(parserOptions, "exportsPresence", "error");
  880. D(parserOptions, "strictModeViolations", futureDefaults ? "error" : "warn");
  881. D(parserOptions, "anonymousDefaultExportName", !library);
  882. };
  883. /**
  884. * Apply json generator options defaults.
  885. * @param {JsonGeneratorOptions} generatorOptions generator options
  886. * @returns {void}
  887. */
  888. const applyJsonGeneratorOptionsDefaults = (generatorOptions) => {
  889. D(generatorOptions, "JSONParse", true);
  890. };
  891. /**
  892. * Apply css generator options defaults.
  893. * @param {CssGeneratorOptions} generatorOptions generator options
  894. * @param {object} options options
  895. * @param {TargetProperties | false} options.targetProperties target properties
  896. * @returns {void}
  897. */
  898. const applyCssGeneratorOptionsDefaults = (
  899. generatorOptions,
  900. { targetProperties }
  901. ) => {
  902. D(
  903. generatorOptions,
  904. "exportsOnly",
  905. !targetProperties || targetProperties.document === false
  906. );
  907. D(generatorOptions, "esModule", true);
  908. };
  909. /**
  910. * Apply module defaults.
  911. * @param {ModuleOptions} module options
  912. * @param {object} options options
  913. * @param {boolean} options.cache is caching enabled
  914. * @param {boolean} options.syncWebAssembly is syncWebAssembly enabled
  915. * @param {boolean} options.asyncWebAssembly is asyncWebAssembly enabled
  916. * @param {boolean} options.typescript is typescript enabled
  917. * @param {boolean} options.css is css enabled
  918. * @param {boolean} options.html is html enabled
  919. * @param {boolean} options.futureDefaults is future defaults enabled
  920. * @param {string} options.uniqueName the unique name
  921. * @param {boolean} options.isNode is node target platform
  922. * @param {boolean} options.deferImport is defer import enabled
  923. * @param {boolean} options.sourceImport is import source enabled
  924. * @param {TargetProperties | false} options.targetProperties target properties
  925. * @param {Mode | undefined} options.mode mode
  926. * @param {HashSalt} options.hashSalt hash salt
  927. * @param {HashFunction} options.hashFunction hash function
  928. * @param {boolean} options.outputModule is output.module enabled
  929. * @param {WebpackOptionsNormalized["output"]["library"]} options.library library options
  930. * @returns {void}
  931. */
  932. const applyModuleDefaults = (
  933. module,
  934. {
  935. hashSalt,
  936. hashFunction,
  937. cache,
  938. syncWebAssembly,
  939. asyncWebAssembly,
  940. css,
  941. html,
  942. typescript,
  943. futureDefaults,
  944. isNode,
  945. uniqueName,
  946. targetProperties,
  947. mode,
  948. deferImport,
  949. sourceImport,
  950. outputModule,
  951. library
  952. }
  953. ) => {
  954. if (cache) {
  955. D(
  956. module,
  957. "unsafeCache",
  958. /**
  959. * Handles the callback logic for this hook.
  960. * @param {Module} module module
  961. * @returns {boolean} true, if we want to cache the module
  962. */
  963. (module) => {
  964. const name = module.nameForCondition();
  965. if (!name) {
  966. return false;
  967. }
  968. return NODE_MODULES_REGEXP.test(name);
  969. }
  970. );
  971. } else {
  972. D(module, "unsafeCache", false);
  973. }
  974. F(module.parser, ASSET_MODULE_TYPE, () => ({}));
  975. F(
  976. /** @type {NonNullable<ParserOptionsByModuleTypeKnown[ASSET_MODULE_TYPE]>} */
  977. (module.parser[ASSET_MODULE_TYPE]),
  978. "dataUrlCondition",
  979. () => ({})
  980. );
  981. if (
  982. typeof (
  983. /** @type {NonNullable<ParserOptionsByModuleTypeKnown[ASSET_MODULE_TYPE]>} */
  984. (module.parser[ASSET_MODULE_TYPE]).dataUrlCondition
  985. ) === "object"
  986. ) {
  987. D(
  988. /** @type {NonNullable<ParserOptionsByModuleTypeKnown[ASSET_MODULE_TYPE]>} */
  989. (module.parser[ASSET_MODULE_TYPE]).dataUrlCondition,
  990. "maxSize",
  991. 8096
  992. );
  993. }
  994. F(module.parser, "javascript", () => ({}));
  995. F(module.parser, JSON_MODULE_TYPE, () => ({}));
  996. D(
  997. /** @type {NonNullable<ParserOptionsByModuleTypeKnown[JSON_MODULE_TYPE]>} */
  998. (module.parser[JSON_MODULE_TYPE]),
  999. "exportsDepth",
  1000. mode === "development" ? 1 : Infinity
  1001. );
  1002. applyJavascriptParserOptionsDefaults(
  1003. /** @type {NonNullable<ParserOptionsByModuleTypeKnown["javascript"]>} */
  1004. (module.parser.javascript),
  1005. {
  1006. futureDefaults,
  1007. deferImport,
  1008. sourceImport,
  1009. isNode,
  1010. outputModule,
  1011. library,
  1012. typescript
  1013. }
  1014. );
  1015. F(module.generator, "json", () => ({}));
  1016. applyJsonGeneratorOptionsDefaults(
  1017. /** @type {NonNullable<GeneratorOptionsByModuleTypeKnown["json"]>} */
  1018. (module.generator.json)
  1019. );
  1020. if (css) {
  1021. F(module.parser, CSS_MODULE_TYPE, () => ({}));
  1022. D(
  1023. /** @type {NonNullable<ParserOptionsByModuleTypeKnown[CSS_MODULE_TYPE]>} */
  1024. (module.parser[CSS_MODULE_TYPE]),
  1025. "import",
  1026. true
  1027. );
  1028. D(
  1029. /** @type {NonNullable<ParserOptionsByModuleTypeKnown[CSS_MODULE_TYPE]>} */
  1030. (module.parser[CSS_MODULE_TYPE]),
  1031. "url",
  1032. true
  1033. );
  1034. D(
  1035. /** @type {NonNullable<ParserOptionsByModuleTypeKnown[CSS_MODULE_TYPE]>} */
  1036. (module.parser[CSS_MODULE_TYPE]),
  1037. "namedExports",
  1038. true
  1039. );
  1040. D(
  1041. /** @type {NonNullable<ParserOptionsByModuleTypeKnown[CSS_MODULE_TYPE]>} */
  1042. (module.parser[CSS_MODULE_TYPE]),
  1043. "customMedia",
  1044. true
  1045. );
  1046. D(
  1047. /** @type {NonNullable<ParserOptionsByModuleTypeKnown[CSS_MODULE_TYPE]>} */
  1048. (module.parser[CSS_MODULE_TYPE]),
  1049. "customSelectors",
  1050. true
  1051. );
  1052. for (const type of [
  1053. CSS_MODULE_TYPE_AUTO,
  1054. CSS_MODULE_TYPE_MODULE,
  1055. CSS_MODULE_TYPE_GLOBAL
  1056. ]) {
  1057. F(module.parser, type, () => ({}));
  1058. D(
  1059. /** @type {NonNullable<ParserOptionsByModuleTypeKnown[CSS_MODULE_TYPE_AUTO]> | NonNullable<ParserOptionsByModuleTypeKnown[CSS_MODULE_TYPE_MODULE]> | NonNullable<ParserOptionsByModuleTypeKnown[CSS_MODULE_TYPE_GLOBAL]>} */
  1060. (module.parser[type]),
  1061. "animation",
  1062. true
  1063. );
  1064. D(
  1065. /** @type {NonNullable<ParserOptionsByModuleTypeKnown[CSS_MODULE_TYPE_AUTO]> | NonNullable<ParserOptionsByModuleTypeKnown[CSS_MODULE_TYPE_MODULE]> | NonNullable<ParserOptionsByModuleTypeKnown[CSS_MODULE_TYPE_GLOBAL]>} */
  1066. (module.parser[type]),
  1067. "container",
  1068. true
  1069. );
  1070. D(
  1071. /** @type {NonNullable<ParserOptionsByModuleTypeKnown[CSS_MODULE_TYPE_AUTO]> | NonNullable<ParserOptionsByModuleTypeKnown[CSS_MODULE_TYPE_MODULE]> | NonNullable<ParserOptionsByModuleTypeKnown[CSS_MODULE_TYPE_GLOBAL]>} */
  1072. (module.parser[type]),
  1073. "customIdents",
  1074. true
  1075. );
  1076. D(
  1077. /** @type {NonNullable<ParserOptionsByModuleTypeKnown[CSS_MODULE_TYPE_AUTO]> | NonNullable<ParserOptionsByModuleTypeKnown[CSS_MODULE_TYPE_MODULE]> | NonNullable<ParserOptionsByModuleTypeKnown[CSS_MODULE_TYPE_GLOBAL]>} */
  1078. (module.parser[type]),
  1079. "dashedIdents",
  1080. true
  1081. );
  1082. D(
  1083. /** @type {NonNullable<ParserOptionsByModuleTypeKnown[CSS_MODULE_TYPE_AUTO]> | NonNullable<ParserOptionsByModuleTypeKnown[CSS_MODULE_TYPE_MODULE]> | NonNullable<ParserOptionsByModuleTypeKnown[CSS_MODULE_TYPE_GLOBAL]>} */
  1084. (module.parser[type]),
  1085. "function",
  1086. true
  1087. );
  1088. D(
  1089. /** @type {NonNullable<ParserOptionsByModuleTypeKnown[CSS_MODULE_TYPE_AUTO]> | NonNullable<ParserOptionsByModuleTypeKnown[CSS_MODULE_TYPE_MODULE]> | NonNullable<ParserOptionsByModuleTypeKnown[CSS_MODULE_TYPE_GLOBAL]>} */
  1090. (module.parser[type]),
  1091. "grid",
  1092. true
  1093. );
  1094. D(
  1095. /** @type {NonNullable<ParserOptionsByModuleTypeKnown[CSS_MODULE_TYPE_AUTO]> | NonNullable<ParserOptionsByModuleTypeKnown[CSS_MODULE_TYPE_MODULE]> | NonNullable<ParserOptionsByModuleTypeKnown[CSS_MODULE_TYPE_GLOBAL]>} */
  1096. (module.parser[type]),
  1097. "customMedia",
  1098. true
  1099. );
  1100. D(
  1101. /** @type {NonNullable<ParserOptionsByModuleTypeKnown[CSS_MODULE_TYPE_AUTO]> | NonNullable<ParserOptionsByModuleTypeKnown[CSS_MODULE_TYPE_MODULE]> | NonNullable<ParserOptionsByModuleTypeKnown[CSS_MODULE_TYPE_GLOBAL]>} */
  1102. (module.parser[type]),
  1103. "customSelectors",
  1104. true
  1105. );
  1106. }
  1107. F(module.generator, CSS_MODULE_TYPE, () => ({}));
  1108. applyCssGeneratorOptionsDefaults(
  1109. /** @type {NonNullable<GeneratorOptionsByModuleTypeKnown[CSS_MODULE_TYPE]>} */
  1110. (module.generator[CSS_MODULE_TYPE]),
  1111. { targetProperties }
  1112. );
  1113. const localIdentName =
  1114. mode === "development"
  1115. ? uniqueName.length > 0
  1116. ? "[uniqueName]-[id]-[local]"
  1117. : "[id]-[local]"
  1118. : "[fullhash]";
  1119. const localIdentHashSalt = hashSalt;
  1120. const localIdentHashDigest = "base64url";
  1121. const localIdentHashDigestLength = 6;
  1122. const exportsConvention = "as-is";
  1123. for (const type of [
  1124. CSS_MODULE_TYPE_AUTO,
  1125. CSS_MODULE_TYPE_MODULE,
  1126. CSS_MODULE_TYPE_GLOBAL
  1127. ]) {
  1128. F(module.generator, type, () => ({}));
  1129. D(
  1130. /** @type {NonNullable<GeneratorOptionsByModuleTypeKnown[CSS_MODULE_TYPE_AUTO]> | NonNullable<GeneratorOptionsByModuleTypeKnown[CSS_MODULE_TYPE_MODULE]> | NonNullable<GeneratorOptionsByModuleTypeKnown[CSS_MODULE_TYPE_GLOBAL]>} */
  1131. (module.generator[type]),
  1132. "localIdentName",
  1133. localIdentName
  1134. );
  1135. D(
  1136. /** @type {NonNullable<GeneratorOptionsByModuleTypeKnown[CSS_MODULE_TYPE_AUTO]> | NonNullable<GeneratorOptionsByModuleTypeKnown[CSS_MODULE_TYPE_MODULE]> | NonNullable<GeneratorOptionsByModuleTypeKnown[CSS_MODULE_TYPE_GLOBAL]>} */
  1137. (module.generator[type]),
  1138. "localIdentHashSalt",
  1139. localIdentHashSalt
  1140. );
  1141. D(
  1142. /** @type {NonNullable<GeneratorOptionsByModuleTypeKnown[CSS_MODULE_TYPE_AUTO]> | NonNullable<GeneratorOptionsByModuleTypeKnown[CSS_MODULE_TYPE_MODULE]> | NonNullable<GeneratorOptionsByModuleTypeKnown[CSS_MODULE_TYPE_MODULE]>} */
  1143. (module.generator[type]),
  1144. "localIdentHashFunction",
  1145. hashFunction
  1146. );
  1147. D(
  1148. /** @type {NonNullable<GeneratorOptionsByModuleTypeKnown[CSS_MODULE_TYPE_AUTO]> | NonNullable<GeneratorOptionsByModuleTypeKnown[CSS_MODULE_TYPE_MODULE]> | NonNullable<GeneratorOptionsByModuleTypeKnown[CSS_MODULE_TYPE_MODULE]>} */
  1149. (module.generator[type]),
  1150. "localIdentHashDigest",
  1151. localIdentHashDigest
  1152. );
  1153. D(
  1154. /** @type {NonNullable<GeneratorOptionsByModuleTypeKnown[CSS_MODULE_TYPE_AUTO]> | NonNullable<GeneratorOptionsByModuleTypeKnown[CSS_MODULE_TYPE_MODULE]> | NonNullable<GeneratorOptionsByModuleTypeKnown[CSS_MODULE_TYPE_MODULE]>} */
  1155. (module.generator[type]),
  1156. "localIdentHashDigestLength",
  1157. localIdentHashDigestLength
  1158. );
  1159. D(
  1160. /** @type {NonNullable<GeneratorOptionsByModuleTypeKnown[CSS_MODULE_TYPE_AUTO]> | NonNullable<GeneratorOptionsByModuleTypeKnown[CSS_MODULE_TYPE_MODULE]> | NonNullable<GeneratorOptionsByModuleTypeKnown[CSS_MODULE_TYPE_GLOBAL]>} */
  1161. (module.generator[type]),
  1162. "exportsConvention",
  1163. exportsConvention
  1164. );
  1165. }
  1166. }
  1167. if (html) {
  1168. // `module.generator.html.extract` is intentionally left undefined by
  1169. // default: HtmlGenerator treats undefined as "extract iff this HTML
  1170. // module is a compilation entry", which is the HTML-entry-point
  1171. // behaviour. Setting `extract: true` forces extraction for all HTML
  1172. // modules (including imported ones); `extract: false` disables it
  1173. // everywhere.
  1174. F(module.generator, HTML_MODULE_TYPE, () => ({}));
  1175. // `module.parser.html.sources` defaults to `true` — HtmlParser uses
  1176. // the built-in source list to extract URL-like attributes (`<img
  1177. // src>`, `<link href>`, `<script src>`, …) as webpack dependencies.
  1178. // Users may pass `false` to disable extraction entirely or an array
  1179. // (with `"..."` to include the defaults) to customize it.
  1180. F(module.parser, HTML_MODULE_TYPE, () => ({}));
  1181. D(
  1182. /** @type {NonNullable<ParserOptionsByModuleTypeKnown[HTML_MODULE_TYPE]>} */
  1183. (module.parser[HTML_MODULE_TYPE]),
  1184. "sources",
  1185. true
  1186. );
  1187. }
  1188. A(module, "defaultRules", () => {
  1189. const esm = {
  1190. type: JAVASCRIPT_MODULE_TYPE_ESM,
  1191. resolve: {
  1192. byDependency: {
  1193. esm: {
  1194. fullySpecified: true
  1195. }
  1196. }
  1197. }
  1198. };
  1199. const commonjs = {
  1200. type: JAVASCRIPT_MODULE_TYPE_DYNAMIC
  1201. };
  1202. /** @type {RuleSetRules} */
  1203. const rules = [
  1204. {
  1205. mimetype: "application/node",
  1206. type: JAVASCRIPT_MODULE_TYPE_AUTO
  1207. },
  1208. {
  1209. test: /\.json$/i,
  1210. type: JSON_MODULE_TYPE
  1211. },
  1212. {
  1213. mimetype: "application/json",
  1214. type: JSON_MODULE_TYPE
  1215. },
  1216. {
  1217. test: /\.mjs$/i,
  1218. ...esm
  1219. },
  1220. {
  1221. test: /\.js$/i,
  1222. descriptionData: {
  1223. type: "module"
  1224. },
  1225. ...esm
  1226. },
  1227. {
  1228. test: /\.cjs$/i,
  1229. ...commonjs
  1230. },
  1231. {
  1232. test: /\.js$/i,
  1233. descriptionData: {
  1234. type: "commonjs"
  1235. },
  1236. ...commonjs
  1237. },
  1238. {
  1239. mimetype: {
  1240. or: ["text/javascript", "application/javascript"]
  1241. },
  1242. ...esm
  1243. }
  1244. ];
  1245. if (asyncWebAssembly) {
  1246. const wasm = {
  1247. type: WEBASSEMBLY_MODULE_TYPE_ASYNC,
  1248. rules: [
  1249. {
  1250. descriptionData: {
  1251. type: "module"
  1252. },
  1253. resolve: {
  1254. fullySpecified: true
  1255. }
  1256. }
  1257. ]
  1258. };
  1259. rules.push({
  1260. test: /\.wasm$/i,
  1261. ...wasm
  1262. });
  1263. rules.push({
  1264. mimetype: "application/wasm",
  1265. ...wasm
  1266. });
  1267. } else if (syncWebAssembly) {
  1268. const wasm = {
  1269. type: WEBASSEMBLY_MODULE_TYPE_SYNC,
  1270. rules: [
  1271. {
  1272. descriptionData: {
  1273. type: "module"
  1274. },
  1275. resolve: {
  1276. fullySpecified: true
  1277. }
  1278. }
  1279. ]
  1280. };
  1281. rules.push({
  1282. test: /\.wasm$/i,
  1283. ...wasm
  1284. });
  1285. rules.push({
  1286. mimetype: "application/wasm",
  1287. ...wasm
  1288. });
  1289. }
  1290. if (css) {
  1291. const resolve = {
  1292. fullySpecified: true,
  1293. preferRelative: true
  1294. };
  1295. rules.push({
  1296. test: /\.css$/i,
  1297. type: CSS_MODULE_TYPE_AUTO,
  1298. resolve
  1299. });
  1300. rules.push({
  1301. mimetype: "text/css+module",
  1302. type: CSS_MODULE_TYPE_MODULE,
  1303. resolve
  1304. });
  1305. rules.push({
  1306. mimetype: "text/css",
  1307. type: CSS_MODULE_TYPE,
  1308. resolve
  1309. });
  1310. // For CSS modules, i.e. `.class { composes: className from "./style.css" }`
  1311. // We inherit for such constructions, but skip files that are already
  1312. // detected as CSS modules by extension (`.module.<ext>`) — they get
  1313. // the same modules-mode behavior from the auto rule, and forcing a
  1314. // different type stamp here would create a duplicate module instance.
  1315. const moduleExtension = /\.module\.\w+$/i;
  1316. rules.push({
  1317. dependency: /css-import-local-module/,
  1318. exclude: moduleExtension,
  1319. type: CSS_MODULE_TYPE_MODULE,
  1320. resolve
  1321. });
  1322. rules.push({
  1323. dependency: /css-import-global-module/,
  1324. exclude: moduleExtension,
  1325. type: CSS_MODULE_TYPE_GLOBAL,
  1326. resolve
  1327. });
  1328. rules.push(
  1329. {
  1330. with: { type: "css" },
  1331. parser: {
  1332. exportType: "css-style-sheet"
  1333. },
  1334. resolve
  1335. },
  1336. {
  1337. assert: { type: "css" },
  1338. parser: {
  1339. exportType: "css-style-sheet"
  1340. },
  1341. resolve
  1342. }
  1343. );
  1344. }
  1345. if (html) {
  1346. const resolve = {
  1347. fullySpecified: true,
  1348. preferRelative: true
  1349. };
  1350. rules.push({
  1351. test: /\.html$/i,
  1352. type: HTML_MODULE_TYPE,
  1353. resolve
  1354. });
  1355. rules.push({
  1356. mimetype: "text/html",
  1357. type: HTML_MODULE_TYPE,
  1358. resolve
  1359. });
  1360. // `<iframe srcdoc>` content is fed back through the HTML pipeline as a
  1361. // `data:text/html` module. `extract: "inline"` exposes the processed
  1362. // HTML on the `html` codegen channel that `HtmlInlineHtmlDependency.
  1363. // Template` reads back into the attribute, without emitting a standalone
  1364. // `.html` file (the module is never a page on its own).
  1365. rules.push({
  1366. dependency: "html-srcdoc",
  1367. generator: {
  1368. extract: "inline"
  1369. },
  1370. resolve
  1371. });
  1372. if (css) {
  1373. // Inline `<style>` content in an HTML module is fed into the
  1374. // CSS pipeline as a `data:text/css` virtual module. We force
  1375. // `exportType: "text"` so the CSS module exposes the
  1376. // processed CSS text on the `css-text` codegen channel that
  1377. // `HtmlInlineStyleDependency.Template` reads back into the
  1378. // `<style>` tag.
  1379. rules.push({
  1380. dependency: "html-style",
  1381. parser: {
  1382. exportType: "text"
  1383. },
  1384. resolve
  1385. });
  1386. // A `style="..."` attribute is a CSS block's contents, not a
  1387. // stylesheet, so parse it as one (`as: "block-contents"`).
  1388. rules.push({
  1389. dependency: "html-style-attribute",
  1390. parser: {
  1391. exportType: "text",
  1392. as: "block-contents"
  1393. },
  1394. resolve
  1395. });
  1396. }
  1397. }
  1398. if (typescript) {
  1399. rules.push(
  1400. {
  1401. test: /\.mts$/i,
  1402. ...esm
  1403. },
  1404. {
  1405. test: /\.ts$/i,
  1406. descriptionData: {
  1407. type: "module"
  1408. },
  1409. ...esm
  1410. },
  1411. {
  1412. test: /\.cts$/i,
  1413. ...commonjs
  1414. },
  1415. {
  1416. test: /\.ts$/i,
  1417. descriptionData: {
  1418. type: "commonjs"
  1419. },
  1420. ...commonjs
  1421. },
  1422. {
  1423. mimetype: {
  1424. or: ["text/typescript", "application/typescript"]
  1425. },
  1426. ...esm
  1427. }
  1428. );
  1429. }
  1430. rules.push(
  1431. {
  1432. dependency: "url",
  1433. oneOf: [
  1434. {
  1435. scheme: /^data$/,
  1436. type: ASSET_MODULE_TYPE_INLINE
  1437. },
  1438. {
  1439. type: ASSET_MODULE_TYPE_RESOURCE
  1440. }
  1441. ]
  1442. },
  1443. {
  1444. with: { type: JSON_MODULE_TYPE },
  1445. type: JSON_MODULE_TYPE,
  1446. parser: { namedExports: false }
  1447. },
  1448. {
  1449. assert: { type: JSON_MODULE_TYPE },
  1450. type: JSON_MODULE_TYPE,
  1451. parser: { namedExports: false }
  1452. },
  1453. {
  1454. with: { type: "text" },
  1455. type: ASSET_MODULE_TYPE_SOURCE
  1456. },
  1457. {
  1458. with: { type: "bytes" },
  1459. type: ASSET_MODULE_TYPE_BYTES
  1460. }
  1461. );
  1462. if (html) {
  1463. // A `.webmanifest` referenced by `<link rel="manifest">` is a `url`
  1464. // dependency; route it to the `asset/webmanifest` type so its icon URLs
  1465. // are parsed. Must come after the generic `url` → asset rule so it wins.
  1466. rules.push({
  1467. dependency: "url",
  1468. test: /\.webmanifest$/i,
  1469. type: "asset/webmanifest"
  1470. });
  1471. // A generated manifest (`output.html.manifest` object) is injected as a
  1472. // `data:application/manifest+json` URL with no `.webmanifest` extension;
  1473. // route it by mimetype so its icons are parsed and hashed too.
  1474. rules.push({
  1475. dependency: "url",
  1476. mimetype: "application/manifest+json",
  1477. type: "asset/webmanifest"
  1478. });
  1479. }
  1480. if (futureDefaults) {
  1481. rules.push({
  1482. oneOf: [
  1483. {
  1484. resourceQuery: /(\?|&)raw(&|$)/,
  1485. type: ASSET_MODULE_TYPE_SOURCE
  1486. },
  1487. {
  1488. resourceQuery: /(\?|&)url(&|$)/,
  1489. type: ASSET_MODULE_TYPE_RESOURCE
  1490. },
  1491. {
  1492. resourceQuery: /(\?|&)no-inline(&|$)/,
  1493. type: ASSET_MODULE_TYPE_RESOURCE
  1494. },
  1495. {
  1496. resourceQuery: /(\?|&)inline(&|$)/,
  1497. type: ASSET_MODULE_TYPE_INLINE
  1498. }
  1499. ]
  1500. });
  1501. }
  1502. return rules;
  1503. });
  1504. };
  1505. /**
  1506. * Apply output defaults.
  1507. * @param {Output} output options
  1508. * @param {object} options options
  1509. * @param {string} options.context context
  1510. * @param {TargetProperties | false} options.targetProperties target properties
  1511. * @param {boolean} options.isAffectedByBrowserslist is affected by browserslist
  1512. * @param {boolean} options.outputModule is outputModule experiment enabled
  1513. * @param {boolean} options.development is development mode
  1514. * @param {Entry} options.entry entry option
  1515. * @param {boolean} options.futureDefaults is future defaults enabled
  1516. * @param {boolean} options.asyncWebAssembly is asyncWebAssembly enabled
  1517. * @returns {void}
  1518. */
  1519. const applyOutputDefaults = (
  1520. output,
  1521. {
  1522. context,
  1523. targetProperties: tp,
  1524. isAffectedByBrowserslist,
  1525. outputModule,
  1526. development,
  1527. entry,
  1528. futureDefaults,
  1529. asyncWebAssembly
  1530. }
  1531. ) => {
  1532. /**
  1533. * Returns a readable library name.
  1534. * @param {Library=} library the library option
  1535. * @returns {string} a readable library name
  1536. */
  1537. const getLibraryName = (library) => {
  1538. const libraryName =
  1539. typeof library === "object" &&
  1540. library &&
  1541. !Array.isArray(library) &&
  1542. "type" in library
  1543. ? library.name
  1544. : /** @type {LibraryName} */ (library);
  1545. if (Array.isArray(libraryName)) {
  1546. return libraryName.join(".");
  1547. } else if (typeof libraryName === "object") {
  1548. return getLibraryName(libraryName.root);
  1549. } else if (typeof libraryName === "string") {
  1550. return libraryName;
  1551. }
  1552. return "";
  1553. };
  1554. F(output, "uniqueName", () => {
  1555. const libraryName = getLibraryName(output.library).replace(
  1556. /^\[(\\*[\w:]+\\*)\](\.)|(\.)\[(\\*[\w:]+\\*)\](?=\.|$)|\[(\\*[\w:]+\\*)\]/g,
  1557. (m, a, d1, d2, b, c) => {
  1558. const content = a || b || c;
  1559. return content.startsWith("\\") && content.endsWith("\\")
  1560. ? `${d2 || ""}[${content.slice(1, -1)}]${d1 || ""}`
  1561. : "";
  1562. }
  1563. );
  1564. if (libraryName) return libraryName;
  1565. const pkgPath = path.resolve(context, "package.json");
  1566. try {
  1567. const packageInfo = JSON.parse(fs.readFileSync(pkgPath, "utf8"));
  1568. return packageInfo.name || "";
  1569. } catch (err) {
  1570. if (/** @type {Error & { code: string }} */ (err).code !== "ENOENT") {
  1571. /** @type {Error & { code: string }} */
  1572. (err).message +=
  1573. `\nwhile determining default 'output.uniqueName' from 'name' in ${pkgPath}`;
  1574. throw err;
  1575. }
  1576. return "";
  1577. }
  1578. });
  1579. F(output, "module", () => Boolean(outputModule));
  1580. const environment = /** @type {Environment} */ (output.environment);
  1581. /**
  1582. * Returns true, when v is truthy or undefined.
  1583. * @param {boolean | undefined} v value
  1584. * @returns {boolean} true, when v is truthy or undefined
  1585. */
  1586. const optimistic = (v) => v || v === undefined;
  1587. /**
  1588. * Conditionally optimistic.
  1589. * @param {boolean | undefined} v value
  1590. * @param {boolean | undefined} c condition
  1591. * @returns {boolean | undefined} true, when v is truthy or undefined, or c is truthy
  1592. */
  1593. const conditionallyOptimistic = (v, c) => (v === undefined && c) || v;
  1594. F(
  1595. environment,
  1596. "globalThis",
  1597. () => /** @type {boolean | undefined} */ (tp && tp.globalThis)
  1598. );
  1599. F(
  1600. environment,
  1601. "symbol",
  1602. () => tp && optimistic(/** @type {boolean | undefined} */ (tp.symbol))
  1603. );
  1604. F(
  1605. environment,
  1606. "hasOwn",
  1607. // No optimistic, because it is new
  1608. () => tp && /** @type {boolean | undefined} */ (tp.hasOwn)
  1609. );
  1610. F(
  1611. environment,
  1612. "bigIntLiteral",
  1613. () =>
  1614. tp && optimistic(/** @type {boolean | undefined} */ (tp.bigIntLiteral))
  1615. );
  1616. F(
  1617. environment,
  1618. "const",
  1619. () => tp && optimistic(/** @type {boolean | undefined} */ (tp.const))
  1620. );
  1621. // Only the browserslist target reports these; everywhere else they stay
  1622. // unset, which `optimistic` reads as the modern spelling being available —
  1623. // the same policy the JS features above follow.
  1624. // `let` was added after `const`; targets predating it report only `const`,
  1625. // so fall back to `const` when `let` is unreported (undefined). Targets that
  1626. // do report `let` (browserslist, built-ins) keep their own accurate value.
  1627. F(environment, "let", () =>
  1628. conditionallyOptimistic(
  1629. /** @type {boolean | undefined} */ (tp && tp.let),
  1630. environment.const
  1631. )
  1632. );
  1633. F(
  1634. environment,
  1635. "logicalAssignment",
  1636. () =>
  1637. // No optimistic, because it is new
  1638. tp && /** @type {boolean | undefined} */ (tp.logicalAssignment)
  1639. );
  1640. F(
  1641. environment,
  1642. "methodShorthand",
  1643. () =>
  1644. tp && optimistic(/** @type {boolean | undefined} */ (tp.methodShorthand))
  1645. );
  1646. F(
  1647. environment,
  1648. "arrowFunction",
  1649. () =>
  1650. tp && optimistic(/** @type {boolean | undefined} */ (tp.arrowFunction))
  1651. );
  1652. F(
  1653. environment,
  1654. "asyncFunction",
  1655. () =>
  1656. tp && optimistic(/** @type {boolean | undefined} */ (tp.asyncFunction))
  1657. );
  1658. F(
  1659. environment,
  1660. "generator",
  1661. () => tp && optimistic(/** @type {boolean | undefined} */ (tp.generator))
  1662. );
  1663. F(
  1664. environment,
  1665. "forOf",
  1666. () => tp && optimistic(/** @type {boolean | undefined} */ (tp.forOf))
  1667. );
  1668. // Stage 3 syntax, so these are the one pair read pessimistically: a preset that
  1669. // says nothing means unavailable, and the phase keeps webpack's own form.
  1670. F(environment, "deferImport", () =>
  1671. Boolean(tp && /** @type {boolean | undefined} */ (tp.deferImport))
  1672. );
  1673. F(environment, "sourceImport", () =>
  1674. Boolean(tp && /** @type {boolean | undefined} */ (tp.sourceImport))
  1675. );
  1676. F(
  1677. environment,
  1678. "destructuring",
  1679. () =>
  1680. tp && optimistic(/** @type {boolean | undefined} */ (tp.destructuring))
  1681. );
  1682. F(
  1683. environment,
  1684. "optionalChaining",
  1685. () =>
  1686. tp && optimistic(/** @type {boolean | undefined} */ (tp.optionalChaining))
  1687. );
  1688. F(
  1689. environment,
  1690. "spread",
  1691. () => tp && optimistic(/** @type {boolean | undefined} */ (tp.spread))
  1692. );
  1693. F(
  1694. environment,
  1695. "nodePrefixForCoreModules",
  1696. () =>
  1697. tp &&
  1698. optimistic(
  1699. /** @type {boolean | undefined} */ (tp.nodePrefixForCoreModules)
  1700. )
  1701. );
  1702. F(
  1703. environment,
  1704. "importMetaDirnameAndFilename",
  1705. () =>
  1706. // No optimistic, because it is new
  1707. tp && /** @type {boolean | undefined} */ (tp.importMetaDirnameAndFilename)
  1708. );
  1709. F(
  1710. environment,
  1711. "nodeBuiltinModuleGetter",
  1712. () =>
  1713. // No optimistic, because it is new
  1714. tp && /** @type {boolean | undefined} */ (tp.nodeBuiltinModuleGetter)
  1715. );
  1716. F(
  1717. environment,
  1718. "templateLiteral",
  1719. () =>
  1720. tp && optimistic(/** @type {boolean | undefined} */ (tp.templateLiteral))
  1721. );
  1722. F(environment, "dynamicImport", () =>
  1723. conditionallyOptimistic(
  1724. /** @type {boolean | undefined} */ (tp && tp.dynamicImport),
  1725. output.module
  1726. )
  1727. );
  1728. F(environment, "dynamicImportInWorker", () =>
  1729. conditionallyOptimistic(
  1730. /** @type {boolean | undefined} */ (tp && tp.dynamicImportInWorker),
  1731. output.module
  1732. )
  1733. );
  1734. F(environment, "module", () =>
  1735. conditionallyOptimistic(
  1736. /** @type {boolean | undefined} */ (tp && tp.module),
  1737. output.module
  1738. )
  1739. );
  1740. F(
  1741. environment,
  1742. "document",
  1743. () => tp && optimistic(/** @type {boolean | undefined} */ (tp.document))
  1744. );
  1745. F(
  1746. environment,
  1747. "modulePreload",
  1748. () =>
  1749. tp && optimistic(/** @type {boolean | undefined} */ (tp.modulePreload))
  1750. );
  1751. // Vite-style default for ESM output (`output.module`): preload the entry's
  1752. // initial dependency graph, which native `import()` would otherwise fetch in
  1753. // a waterfall. Classic output loads initial chunks via parallel `<script>`
  1754. // tags (no waterfall), so it stays opt-in.
  1755. if (output.module && output.resourceHints === undefined) {
  1756. output.resourceHints = {};
  1757. }
  1758. if (output.resourceHints) {
  1759. D(output.resourceHints, "dedupe", false);
  1760. if (output.module) D(output.resourceHints, "initial", true);
  1761. // `modulePreloadPolyfill` defaults from the target's modulepreload
  1762. // support: inject the polyfill iff the environment lacks it.
  1763. D(
  1764. output.resourceHints,
  1765. "modulePreloadPolyfill",
  1766. !environment.modulePreload
  1767. );
  1768. }
  1769. D(output, "filename", output.module ? "[name].mjs" : "[name].js");
  1770. F(output, "iife", () => !output.module);
  1771. D(output, "importFunctionName", "import");
  1772. D(output, "importMetaName", "import.meta");
  1773. F(output, "chunkFilename", () => {
  1774. const filename =
  1775. /** @type {NonNullable<Output["chunkFilename"]>} */
  1776. (output.filename);
  1777. if (typeof filename !== "function") {
  1778. const hasName = filename.includes("[name]");
  1779. const hasId = filename.includes("[id]");
  1780. const hasChunkHash = filename.includes("[chunkhash]");
  1781. const hasContentHash = filename.includes("[contenthash]");
  1782. // Anything changing depending on chunk is fine
  1783. if (hasChunkHash || hasContentHash || hasName || hasId) return filename;
  1784. // Otherwise prefix "[id]." in front of the basename to make it changing
  1785. return filename.replace(/(^|\/)([^/]*(?:\?|$))/, "$1[id].$2");
  1786. }
  1787. return output.module ? "[id].mjs" : "[id].js";
  1788. });
  1789. F(output, "cssFilename", () => {
  1790. const filename =
  1791. /** @type {NonNullable<Output["cssFilename"]>} */
  1792. (output.filename);
  1793. if (typeof filename !== "function") {
  1794. return filename.replace(/\.[mc]?js(\?|$)/, ".css$1");
  1795. }
  1796. return "[id].css";
  1797. });
  1798. F(output, "cssChunkFilename", () => {
  1799. const chunkFilename =
  1800. /** @type {NonNullable<Output["cssChunkFilename"]>} */
  1801. (output.chunkFilename);
  1802. if (typeof chunkFilename !== "function") {
  1803. return chunkFilename.replace(/\.[mc]?js(\?|$)/, ".css$1");
  1804. }
  1805. return "[id].css";
  1806. });
  1807. // Derive html filename defaults from `output.filename` / `output.chunkFilename`
  1808. // (the same shape the CSS pipeline uses), but if the derived template lacks
  1809. // any per-module differentiator, fall back to `[name].html` so multiple
  1810. // extracted HTML modules in one compilation don't collide on the same
  1811. // emitted file. For example: `output.filename: "bundle.js"` would derive
  1812. // `bundle.html` — two `.html` modules extracted in the same build would
  1813. // both want that name and conflict at emit time.
  1814. const HAS_PATH_PLACEHOLDER_REGEXP =
  1815. /\[(name|id|chunkhash|contenthash|fullhash|hash)/;
  1816. /**
  1817. * @param {string} template html filename template derived from `output.filename`
  1818. * @returns {string} same template, or `[name].html` if it has no per-module placeholder
  1819. */
  1820. const ensureUniqueHtmlTemplate = (template) =>
  1821. HAS_PATH_PLACEHOLDER_REGEXP.test(template) ? template : "[name].html";
  1822. F(output, "htmlFilename", () => {
  1823. const filename =
  1824. /** @type {NonNullable<Output["htmlFilename"]>} */
  1825. (output.filename);
  1826. if (typeof filename !== "function") {
  1827. return ensureUniqueHtmlTemplate(
  1828. filename.replace(/\.[mc]?js(\?|$)/, ".html$1")
  1829. );
  1830. }
  1831. return "[name].html";
  1832. });
  1833. F(output, "htmlChunkFilename", () => {
  1834. const chunkFilename =
  1835. /** @type {NonNullable<Output["htmlChunkFilename"]>} */
  1836. (output.chunkFilename);
  1837. if (typeof chunkFilename !== "function") {
  1838. return ensureUniqueHtmlTemplate(
  1839. chunkFilename.replace(/\.[mc]?js(\?|$)/, ".html$1")
  1840. );
  1841. }
  1842. return "[name].html";
  1843. });
  1844. D(output, "html", false);
  1845. D(output, "assetModuleFilename", "[hash][ext][query][fragment]");
  1846. D(output, "webassemblyModuleFilename", "[hash].module.wasm");
  1847. // On by default like other wasm toolchains; set false to drop the fallback runtime code.
  1848. D(output, "wasmStreamingFallback", true);
  1849. D(output, "compareBeforeEmit", true);
  1850. D(output, "charset", !futureDefaults);
  1851. const uniqueNameId = Template.toIdentifier(
  1852. /** @type {NonNullable<Output["uniqueName"]>} */ (output.uniqueName)
  1853. );
  1854. F(output, "hotUpdateGlobal", () => `webpackHotUpdate${uniqueNameId}`);
  1855. F(output, "chunkLoadingGlobal", () => `webpackChunk${uniqueNameId}`);
  1856. F(output, "globalObject", () => {
  1857. if (tp) {
  1858. if (tp.global) return "global";
  1859. if (tp.globalThis) return "globalThis";
  1860. // Universal target (web + node): no one identifier is defined on both
  1861. // sides, so `globalThis` where the target reports nothing against it,
  1862. // and a guarded pair where it does — `self` covers window and worker
  1863. // scopes, `global` covers Node.js. Naming either alone leaves the other
  1864. // platform reading an undeclared binding.
  1865. if (tp.web === null && tp.node === null) {
  1866. return tp.globalThis === undefined
  1867. ? "globalThis"
  1868. : 'typeof self !== "undefined" ? self : global';
  1869. }
  1870. }
  1871. return "self";
  1872. });
  1873. F(output, "chunkFormat", () => {
  1874. if (tp) {
  1875. const helpMessage = isAffectedByBrowserslist
  1876. ? "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."
  1877. : "Select an appropriate 'target' to allow selecting one by default, or specify the 'output.chunkFormat' directly.";
  1878. if (output.module) {
  1879. if (environment.dynamicImport) return "module";
  1880. if (tp.document) return "array-push";
  1881. throw new Error(
  1882. "For the selected environment is no default ESM chunk format available:\n" +
  1883. "ESM exports can be chosen when 'import()' is available.\n" +
  1884. `JSONP Array push can be chosen when 'document' is available.\n${helpMessage}`
  1885. );
  1886. } else {
  1887. if (tp.document) return "array-push";
  1888. if (tp.require) return "commonjs";
  1889. if (tp.nodeBuiltins) return "commonjs";
  1890. if (tp.importScripts) return "array-push";
  1891. throw new Error(
  1892. "For the selected environment is no default script chunk format available:\n" +
  1893. `${
  1894. tp.module
  1895. ? "Module ('module') can be chosen when ES modules are available (please set 'experiments.outputModule' and 'output.module' to `true`)"
  1896. : ""
  1897. }\n` +
  1898. "JSONP Array push ('array-push') can be chosen when 'document' or 'importScripts' is available.\n" +
  1899. `CommonJs exports ('commonjs') can be chosen when 'require' or node builtins are available.\n${helpMessage}`
  1900. );
  1901. }
  1902. }
  1903. throw new Error(
  1904. "Chunk format can't be selected by default when no target is specified"
  1905. );
  1906. });
  1907. D(output, "asyncChunks", true);
  1908. F(output, "chunkLoading", () => {
  1909. if (tp) {
  1910. switch (output.chunkFormat) {
  1911. case "array-push":
  1912. if (tp.document) return "jsonp";
  1913. if (tp.importScripts) return "import-scripts";
  1914. break;
  1915. case "commonjs":
  1916. if (tp.require) return "require";
  1917. if (tp.nodeBuiltins) return "async-node";
  1918. break;
  1919. case "module":
  1920. if (environment.dynamicImport) return "import";
  1921. break;
  1922. }
  1923. if (
  1924. (tp.require === null ||
  1925. tp.nodeBuiltins === null ||
  1926. tp.document === null ||
  1927. tp.importScripts === null) &&
  1928. output.module &&
  1929. environment.dynamicImport
  1930. ) {
  1931. return "import";
  1932. }
  1933. }
  1934. return false;
  1935. });
  1936. F(
  1937. output,
  1938. "workerChunkFilename",
  1939. () =>
  1940. /** @type {NonNullable<Output["workerChunkFilename"]>} */
  1941. (output.chunkFilename)
  1942. );
  1943. F(output, "workerChunkLoading", () => {
  1944. if (tp) {
  1945. switch (output.chunkFormat) {
  1946. case "array-push":
  1947. if (tp.importScriptsInWorker) return "import-scripts";
  1948. break;
  1949. case "commonjs":
  1950. if (tp.require) return "require";
  1951. if (tp.nodeBuiltins) return "async-node";
  1952. break;
  1953. case "module":
  1954. if (environment.dynamicImportInWorker) return "import";
  1955. break;
  1956. }
  1957. if (
  1958. (tp.require === null ||
  1959. tp.nodeBuiltins === null ||
  1960. tp.importScriptsInWorker === null) &&
  1961. output.module &&
  1962. environment.dynamicImportInWorker
  1963. ) {
  1964. return "import";
  1965. }
  1966. }
  1967. return false;
  1968. });
  1969. F(output, "wasmLoading", () => {
  1970. if (tp) {
  1971. if (tp.fetchWasm) return "fetch";
  1972. if (tp.nodeBuiltins) return "async-node";
  1973. if (
  1974. (tp.nodeBuiltins === null || tp.fetchWasm === null) &&
  1975. output.module &&
  1976. environment.dynamicImport
  1977. ) {
  1978. return "universal";
  1979. }
  1980. }
  1981. return false;
  1982. });
  1983. F(output, "workerWasmLoading", () => output.wasmLoading);
  1984. F(output, "devtoolNamespace", () => output.uniqueName);
  1985. if (output.library) {
  1986. F(output.library, "type", () => (output.module ? "module" : "var"));
  1987. }
  1988. F(output, "path", () => path.join(process.cwd(), "dist"));
  1989. F(output, "pathinfo", () => development);
  1990. D(output, "sourceMapFilename", "[file].map[query]");
  1991. D(
  1992. output,
  1993. "hotUpdateChunkFilename",
  1994. `[id].[fullhash].hot-update.${output.module ? "mjs" : "js"}`
  1995. );
  1996. D(
  1997. output,
  1998. "hotUpdateMainFilename",
  1999. // Only `chunkLoading: "import"` loads the manifest via `import()` (needs an
  2000. // `export default` ES module); every other loader fetches it as raw JSON.
  2001. `[runtime].[fullhash].hot-update.${
  2002. output.chunkLoading === "import" ? "json.mjs" : "json"
  2003. }`
  2004. );
  2005. D(output, "crossOriginLoading", false);
  2006. F(output, "scriptType", () => (output.module ? "module" : false));
  2007. D(
  2008. output,
  2009. "publicPath",
  2010. (tp && (tp.document || tp.importScripts)) || output.scriptType === "module"
  2011. ? "auto"
  2012. : ""
  2013. );
  2014. D(output, "workerPublicPath", "");
  2015. D(output, "chunkLoadTimeout", 120000);
  2016. F(output, "hashFunction", () => {
  2017. if (futureDefaults) {
  2018. DEFAULTS.HASH_FUNCTION = "xxhash64";
  2019. return "xxhash64";
  2020. }
  2021. return "md4";
  2022. });
  2023. D(output, "hashDigest", "hex");
  2024. D(output, "hashDigestLength", futureDefaults ? 16 : 20);
  2025. D(output, "strictModuleErrorHandling", false);
  2026. D(output, "strictModuleExceptionHandling", false);
  2027. F(output, "strictModuleResolution", () => development);
  2028. const { trustedTypes } = output;
  2029. if (trustedTypes) {
  2030. F(
  2031. trustedTypes,
  2032. "policyName",
  2033. () =>
  2034. /** @type {NonNullable<Output["uniqueName"]>} */
  2035. (output.uniqueName).replace(/[^a-z0-9\-#=_/@.%]+/gi, "_") || "webpack"
  2036. );
  2037. D(trustedTypes, "onPolicyCreationFailure", "stop");
  2038. }
  2039. /**
  2040. * Processes the provided fn.
  2041. * @param {(entryDescription: EntryDescription) => void} fn iterator
  2042. * @returns {void}
  2043. */
  2044. const forEachEntry = (fn) => {
  2045. for (const name of Object.keys(entry)) {
  2046. fn(/** @type {{ [k: string]: EntryDescription }} */ (entry)[name]);
  2047. }
  2048. };
  2049. A(output, "enabledLibraryTypes", () => {
  2050. /** @type {LibraryType[]} */
  2051. const enabledLibraryTypes = [];
  2052. if (output.library) {
  2053. enabledLibraryTypes.push(output.library.type);
  2054. }
  2055. forEachEntry((desc) => {
  2056. if (desc.library) {
  2057. enabledLibraryTypes.push(desc.library.type);
  2058. }
  2059. });
  2060. return enabledLibraryTypes;
  2061. });
  2062. A(output, "enabledChunkLoadingTypes", () => {
  2063. /** @type {ChunkLoadingTypes} */
  2064. const enabledChunkLoadingTypes = new Set();
  2065. if (output.chunkLoading) {
  2066. enabledChunkLoadingTypes.add(output.chunkLoading);
  2067. }
  2068. if (output.workerChunkLoading) {
  2069. enabledChunkLoadingTypes.add(output.workerChunkLoading);
  2070. }
  2071. forEachEntry((desc) => {
  2072. if (desc.chunkLoading) {
  2073. enabledChunkLoadingTypes.add(desc.chunkLoading);
  2074. }
  2075. });
  2076. return [...enabledChunkLoadingTypes];
  2077. });
  2078. A(output, "enabledWasmLoadingTypes", () => {
  2079. /** @type {WasmLoadingTypes} */
  2080. const enabledWasmLoadingTypes = new Set();
  2081. if (output.wasmLoading) {
  2082. enabledWasmLoadingTypes.add(output.wasmLoading);
  2083. }
  2084. if (output.workerWasmLoading) {
  2085. enabledWasmLoadingTypes.add(output.workerWasmLoading);
  2086. }
  2087. forEachEntry((desc) => {
  2088. if (desc.wasmLoading) {
  2089. enabledWasmLoadingTypes.add(desc.wasmLoading);
  2090. }
  2091. });
  2092. return [...enabledWasmLoadingTypes];
  2093. });
  2094. };
  2095. /**
  2096. * Apply externals presets defaults.
  2097. * @param {ExternalsPresets} externalsPresets options
  2098. * @param {object} options options
  2099. * @param {TargetProperties | false} options.targetProperties target properties
  2100. * @param {boolean} options.buildHttp buildHttp experiment enabled
  2101. * @param {boolean} options.outputModule is output type is module
  2102. * @returns {void}
  2103. */
  2104. const applyExternalsPresetsDefaults = (
  2105. externalsPresets,
  2106. { targetProperties, buildHttp, outputModule }
  2107. ) => {
  2108. /**
  2109. * Checks whether this object is universal.
  2110. * @param {keyof TargetProperties} key a key
  2111. * @returns {boolean} true when target is universal, otherwise false
  2112. */
  2113. const isUniversal = (key) =>
  2114. Boolean(outputModule && targetProperties && targetProperties[key] === null);
  2115. D(
  2116. externalsPresets,
  2117. "web",
  2118. /** @type {boolean | undefined} */
  2119. (
  2120. !buildHttp &&
  2121. targetProperties &&
  2122. (targetProperties.web || isUniversal("node"))
  2123. )
  2124. );
  2125. D(
  2126. externalsPresets,
  2127. "node",
  2128. /** @type {boolean | undefined} */
  2129. (
  2130. targetProperties &&
  2131. ((targetProperties.node &&
  2132. !targetProperties.deno &&
  2133. !targetProperties.bun) ||
  2134. isUniversal("node"))
  2135. )
  2136. );
  2137. // Opt-in only: never auto-externalize installed packages, it would change existing builds.
  2138. D(externalsPresets, "nodeModules", false);
  2139. D(
  2140. externalsPresets,
  2141. "deno",
  2142. /** @type {boolean | undefined} */
  2143. (Boolean(targetProperties && targetProperties.deno))
  2144. );
  2145. D(
  2146. externalsPresets,
  2147. "bun",
  2148. /** @type {boolean | undefined} */
  2149. (Boolean(targetProperties && targetProperties.bun))
  2150. );
  2151. D(
  2152. externalsPresets,
  2153. "nwjs",
  2154. /** @type {boolean | undefined} */
  2155. (targetProperties && (targetProperties.nwjs || isUniversal("nwjs")))
  2156. );
  2157. D(
  2158. externalsPresets,
  2159. "electron",
  2160. /** @type {boolean | undefined} */
  2161. ((targetProperties && targetProperties.electron) || isUniversal("electron"))
  2162. );
  2163. D(
  2164. externalsPresets,
  2165. "electronMain",
  2166. /** @type {boolean | undefined} */
  2167. (
  2168. targetProperties &&
  2169. targetProperties.electron &&
  2170. (targetProperties.electronMain || isUniversal("electronMain"))
  2171. )
  2172. );
  2173. D(
  2174. externalsPresets,
  2175. "electronPreload",
  2176. /** @type {boolean | undefined} */
  2177. (
  2178. targetProperties &&
  2179. targetProperties.electron &&
  2180. (targetProperties.electronPreload || isUniversal("electronPreload"))
  2181. )
  2182. );
  2183. D(
  2184. externalsPresets,
  2185. "electronRenderer",
  2186. /** @type {boolean | undefined} */
  2187. (
  2188. targetProperties &&
  2189. targetProperties.electron &&
  2190. (targetProperties.electronRenderer || isUniversal("electronRenderer"))
  2191. )
  2192. );
  2193. };
  2194. /**
  2195. * Apply loader defaults.
  2196. * @param {Loader} loader options
  2197. * @param {object} options options
  2198. * @param {TargetProperties | false} options.targetProperties target properties
  2199. * @param {Environment} options.environment environment
  2200. * @param {boolean} options.outputModule is output type is module
  2201. * @returns {void}
  2202. */
  2203. const applyLoaderDefaults = (
  2204. loader,
  2205. { targetProperties, environment, outputModule }
  2206. ) => {
  2207. F(loader, "target", () => {
  2208. if (targetProperties) {
  2209. if (targetProperties.electron) {
  2210. if (targetProperties.electronMain) return "electron-main";
  2211. if (targetProperties.electronPreload) return "electron-preload";
  2212. if (targetProperties.electronRenderer) return "electron-renderer";
  2213. return "electron";
  2214. }
  2215. if (targetProperties.nwjs) return "nwjs";
  2216. if (targetProperties.deno) return "deno";
  2217. if (targetProperties.bun) return "bun";
  2218. if (targetProperties.node) return "node";
  2219. if (targetProperties.web) return "web";
  2220. // no single platform to report: the bundle runs on both (target
  2221. // `"universal"` / `["web", "node"]`), so loaders get `"universal"`
  2222. if (
  2223. outputModule &&
  2224. targetProperties.node === null &&
  2225. targetProperties.web === null
  2226. ) {
  2227. return "universal";
  2228. }
  2229. }
  2230. });
  2231. D(loader, "environment", environment);
  2232. };
  2233. /**
  2234. * Apply node defaults.
  2235. * @param {WebpackNode} node options
  2236. * @param {object} options options
  2237. * @param {TargetProperties | false} options.targetProperties target properties
  2238. * @param {boolean} options.futureDefaults is future defaults enabled
  2239. * @param {boolean} options.outputModule is output type is module
  2240. * @returns {void}
  2241. */
  2242. const applyNodeDefaults = (
  2243. node,
  2244. { futureDefaults, outputModule, targetProperties }
  2245. ) => {
  2246. if (node === false) return;
  2247. F(node, "global", () => {
  2248. if (targetProperties && targetProperties.global) return false;
  2249. // We use `warm` because overriding `global` with `globalThis` (or a polyfill) is sometimes safe (global.URL), sometimes unsafe (global.process), but we need to warn about it
  2250. return futureDefaults ? "warn" : true;
  2251. });
  2252. const handlerForNames = () => {
  2253. // TODO webpack@6 remove `node-module` in favor of `eval-only`
  2254. if (targetProperties) {
  2255. if (targetProperties.node) {
  2256. return "eval-only";
  2257. }
  2258. // For the "universal" target we only evaluate these values
  2259. if (
  2260. outputModule &&
  2261. targetProperties.node === null &&
  2262. targetProperties.web === null
  2263. ) {
  2264. return "eval-only";
  2265. }
  2266. }
  2267. // TODO webpack@6 should we use `warn-even-only`?
  2268. return futureDefaults ? "warn-mock" : "mock";
  2269. };
  2270. F(node, "__filename", handlerForNames);
  2271. F(node, "__dirname", handlerForNames);
  2272. };
  2273. /**
  2274. * Apply performance defaults.
  2275. * @param {Performance} performance options
  2276. * @param {object} options options
  2277. * @param {boolean} options.production is production
  2278. * @returns {void}
  2279. */
  2280. const applyPerformanceDefaults = (performance, { production }) => {
  2281. if (performance === false) return;
  2282. D(performance, "maxAssetSize", 250000);
  2283. D(performance, "maxEntrypointSize", 250000);
  2284. // Stands in for every check left unset, so an explicit one still wins.
  2285. const all = performance.all !== undefined ? performance.all : false;
  2286. D(performance, "asyncChunkWaterfalls", all);
  2287. D(performance, "broadContexts", all);
  2288. D(performance, "cacheEffectiveness", all);
  2289. D(performance, "circularDependencies", all);
  2290. D(performance, "conflictingResourceHints", all);
  2291. D(performance, "duplicateModules", all);
  2292. D(performance, "duplicatePackages", all);
  2293. D(performance, "dynamicExports", all);
  2294. D(performance, "entrypointOverlap", all);
  2295. D(performance, "embeddedSourceMaps", all);
  2296. D(performance, "evalUsage", all);
  2297. D(performance, "hotspots", all);
  2298. D(performance, "legacyJavascript", all);
  2299. D(performance, "largeModules", all);
  2300. D(performance, "inlinedAssets", all);
  2301. D(performance, "mixedExports", all);
  2302. D(performance, "missingSideEffects", all);
  2303. D(performance, "osDependentRules", all);
  2304. D(performance, "pureAnnotations", all);
  2305. D(performance, "redundantDynamicImports", all);
  2306. D(performance, "scopeHoistingBailouts", all);
  2307. D(performance, "splitChunksCapped", all);
  2308. D(performance, "tinyChunks", all);
  2309. D(performance, "topLevelThis", all);
  2310. D(performance, "unsplitVendors", all);
  2311. D(performance, "unusedAliases", all);
  2312. D(performance, "unusedDefines", all);
  2313. D(performance, "unusedExternals", all);
  2314. D(performance, "unusedReexports", all);
  2315. D(performance, "unusedRules", all);
  2316. F(performance, "hints", () => (production ? "warning" : false));
  2317. };
  2318. /**
  2319. * Apply optimization defaults.
  2320. * @param {Optimization} optimization options
  2321. * @param {object} options options
  2322. * @param {boolean} options.production is production
  2323. * @param {boolean} options.development is development
  2324. * @param {boolean} options.css is css enabled
  2325. * @param {boolean} options.records using records
  2326. * @returns {void}
  2327. */
  2328. const applyOptimizationDefaults = (
  2329. optimization,
  2330. { production, development, css, records }
  2331. ) => {
  2332. D(optimization, "removeAvailableModules", false);
  2333. D(optimization, "removeEmptyChunks", true);
  2334. D(optimization, "mergeDuplicateChunks", true);
  2335. D(optimization, "flagIncludedChunks", production);
  2336. F(optimization, "moduleIds", () => {
  2337. if (production) return "deterministic";
  2338. if (development) return "named";
  2339. return "natural";
  2340. });
  2341. F(optimization, "chunkIds", () => {
  2342. if (production) return "deterministic";
  2343. if (development) return "named";
  2344. return "natural";
  2345. });
  2346. F(optimization, "sideEffects", () => (production ? true : "flag"));
  2347. D(optimization, "providedExports", true);
  2348. D(optimization, "usedExports", production);
  2349. D(optimization, "innerGraph", production);
  2350. D(optimization, "inlineExports", production);
  2351. D(optimization, "mangleExports", production);
  2352. D(optimization, "concatenateModules", production);
  2353. D(optimization, "avoidEntryIife", production);
  2354. D(optimization, "runtimeChunk", false);
  2355. D(optimization, "emitOnErrors", !production);
  2356. D(optimization, "checkWasmTypes", production);
  2357. D(optimization, "mangleWasmImports", false);
  2358. D(optimization, "portableRecords", records);
  2359. D(optimization, "realContentHash", production);
  2360. F(optimization, "minimize", () => (production ? {} : false));
  2361. // A plugin can assign the `true` shorthand in `apply()`, which runs after
  2362. // `getNormalizedOptimizationMinimize` and so never gets normalized. The
  2363. // normalized type does not allow it, hence the cast.
  2364. if (/** @type {unknown} */ (optimization.minimize) === true) {
  2365. optimization.minimize = {};
  2366. }
  2367. const { minimize } = optimization;
  2368. if (minimize) {
  2369. // Canonicalize the object form: the JS minimizer's defaults become
  2370. // visible in the resolved config rather than hidden in the wiring.
  2371. F(minimize, "javascript", () => ({ compress: { passes: 2 } }));
  2372. F(minimize, "css", () => ({}));
  2373. F(minimize, "html", () => ({}));
  2374. }
  2375. A(optimization, "minimizer", () => [
  2376. {
  2377. apply: (compiler) => {
  2378. // Lazy load the minimizer plugin
  2379. const TerserPlugin = require("minimizer-webpack-plugin");
  2380. // One minimizer instance (one worker-thread pool) handles JS and, when
  2381. // native CSS / HTML is enabled, those assets too — an array of minify
  2382. // functions each dispatched by its own `filter` (terser -> JS,
  2383. // cssMinify -> CSS, htmlMinify -> HTML). The CSS / HTML serializers stay
  2384. // worker-safe by resolving their parser with `require("webpack/…")` in
  2385. // the worker, so all three share the same pool. `test` is widened to let
  2386. // CSS / HTML assets reach the dispatcher.
  2387. // Step aside for a minimizer the user already configured for these
  2388. // types: whichever of the two ran first would mark the asset
  2389. // `minimized` and silently disable the other, so webpack only claims
  2390. // what nothing else does. Their asset matchers are read directly rather
  2391. // than resolved per asset — a coarse check, but it keeps the outcome
  2392. // independent of tap order and of the plugin version in use.
  2393. const claimedByOtherMinimizer = require("./getClaimedAssetTypes")(
  2394. compiler
  2395. );
  2396. // Normalized + defaulted `optimization.minimize` is the per-asset-type
  2397. // object here: `false` disables a type, an object is its options.
  2398. const minimizeByType = /** @type {OptimizationMinimizeOptions} */ (
  2399. compiler.options.optimization.minimize
  2400. );
  2401. const terserOptions = minimizeByType.javascript || {
  2402. compress: { passes: 2 }
  2403. };
  2404. const { css, html } = compiler.options.experiments;
  2405. const minifyJs = minimizeByType.javascript !== false;
  2406. const minifyCss =
  2407. Boolean(css) &&
  2408. !claimedByOtherMinimizer.css &&
  2409. minimizeByType.css !== false;
  2410. const minifyHtml =
  2411. Boolean(html) &&
  2412. !claimedByOtherMinimizer.html &&
  2413. minimizeByType.html !== false;
  2414. if (!minifyJs && !minifyCss && !minifyHtml) return;
  2415. if (minifyJs && !minifyCss && !minifyHtml) {
  2416. new TerserPlugin({ terserOptions }).apply(
  2417. /** @type {EXPECTED_ANY} */ (compiler)
  2418. );
  2419. return;
  2420. }
  2421. /** @type {(typeof TerserPlugin.terserMinify | typeof import("../css/cssMinify") | typeof import("../html/htmlMinify"))[]} */
  2422. const minify = [];
  2423. /** @type {EXPECTED_OBJECT[]} */
  2424. const minimizerOptions = [];
  2425. /** @type {string[]} */
  2426. const extensions = [];
  2427. // `minimize.css` follows the CSS minifier wherever it runs: the HTML
  2428. // entry gets the same options, like the shared environment below.
  2429. const cssOptions =
  2430. typeof minimizeByType.css === "object"
  2431. ? minimizeByType.css
  2432. : undefined;
  2433. // The browserslist selection, when the target is one. It decides both the
  2434. // prefixes and every spelling a target can read, so `vendorPrefixes`
  2435. // turns off the first alone — resolving it is what the second needs.
  2436. const { target } = compiler.options;
  2437. const browsers = target
  2438. ? getTargetsBrowsers(
  2439. Array.isArray(target) ? target : [target],
  2440. /** @type {Context} */ (compiler.options.context)
  2441. )
  2442. : undefined;
  2443. const cssEnvironment = {
  2444. browsers,
  2445. vendorPrefixes:
  2446. cssOptions === undefined || cssOptions.vendorPrefixes !== false
  2447. };
  2448. const htmlOptions =
  2449. typeof minimizeByType.html === "object"
  2450. ? minimizeByType.html
  2451. : undefined;
  2452. if (minifyJs) {
  2453. minify.push(TerserPlugin.terserMinify);
  2454. minimizerOptions.push(terserOptions);
  2455. extensions.push("[cm]?js");
  2456. }
  2457. if (minifyCss) {
  2458. minify.push(require("../css/cssMinify"));
  2459. minimizerOptions.push({
  2460. environment: cssEnvironment,
  2461. ...cssOptions
  2462. });
  2463. extensions.push("css");
  2464. }
  2465. if (minifyHtml) {
  2466. minify.push(require("../html/htmlMinify"));
  2467. // `minimize.css` rides along under its own key rather than spread
  2468. // beside the HTML options: the two name some of the same switches
  2469. // (`quotes`, `comments`), and one flat object would hand
  2470. // each language the other's answer.
  2471. minimizerOptions.push({
  2472. environment: cssEnvironment,
  2473. css: cssOptions,
  2474. ...htmlOptions
  2475. });
  2476. extensions.push("html");
  2477. }
  2478. new TerserPlugin({
  2479. test: new RegExp(`\\.(?:${extensions.join("|")})(\\?.*)?$`, "i"),
  2480. minify,
  2481. minimizerOptions
  2482. }).apply(/** @type {EXPECTED_ANY} */ (compiler));
  2483. }
  2484. }
  2485. ]);
  2486. F(optimization, "nodeEnv", () => {
  2487. if (production) return "production";
  2488. if (development) return "development";
  2489. return false;
  2490. });
  2491. const { splitChunks } = optimization;
  2492. if (splitChunks) {
  2493. A(splitChunks, "defaultSizeTypes", () =>
  2494. css
  2495. ? [JAVASCRIPT_TYPE, CSS_TYPE, UNKNOWN_TYPE]
  2496. : [JAVASCRIPT_TYPE, UNKNOWN_TYPE]
  2497. );
  2498. D(splitChunks, "hidePathInfo", production);
  2499. D(splitChunks, "chunks", "async");
  2500. D(splitChunks, "usedExports", optimization.usedExports === true);
  2501. D(splitChunks, "minChunks", 1);
  2502. F(splitChunks, "minSize", () => (production ? 20000 : 10000));
  2503. F(splitChunks, "minRemainingSize", () => (development ? 0 : undefined));
  2504. F(splitChunks, "enforceSizeThreshold", () => (production ? 50000 : 30000));
  2505. F(splitChunks, "maxAsyncRequests", () => (production ? 30 : Infinity));
  2506. F(splitChunks, "maxInitialRequests", () => (production ? 30 : Infinity));
  2507. D(splitChunks, "automaticNameDelimiter", "-");
  2508. const cacheGroups =
  2509. /** @type {NonNullable<OptimizationSplitChunksOptions["cacheGroups"]>} */
  2510. (splitChunks.cacheGroups);
  2511. F(cacheGroups, "default", () => ({
  2512. idHint: "",
  2513. reuseExistingChunk: true,
  2514. minChunks: 2,
  2515. priority: -20
  2516. }));
  2517. F(cacheGroups, "defaultVendors", () => ({
  2518. idHint: "vendors",
  2519. reuseExistingChunk: true,
  2520. test: NODE_MODULES_REGEXP,
  2521. priority: -10
  2522. }));
  2523. }
  2524. };
  2525. /**
  2526. * Gets resolve defaults.
  2527. * @param {object} options options
  2528. * @param {boolean} options.cache is cache enable
  2529. * @param {string} options.context build context
  2530. * @param {TargetProperties | false} options.targetProperties target properties
  2531. * @param {Mode} options.mode mode
  2532. * @param {boolean} options.css is css enabled
  2533. * @param {boolean} options.html is html enabled
  2534. * @param {boolean} options.htmlFirst whether `.html` should outrank `.js` when resolving (only when html was explicitly enabled)
  2535. * @param {boolean} options.typescript is typescript enabled
  2536. * @returns {ResolveOptions} resolve options
  2537. */
  2538. const getResolveDefaults = ({
  2539. cache,
  2540. context,
  2541. targetProperties,
  2542. mode,
  2543. css,
  2544. html,
  2545. htmlFirst,
  2546. typescript
  2547. }) => {
  2548. /** @type {string[]} */
  2549. const conditions = ["webpack"];
  2550. conditions.push(mode === "development" ? "development" : "production");
  2551. if (targetProperties) {
  2552. if (targetProperties.deno) conditions.push("deno");
  2553. if (targetProperties.bun) conditions.push("bun");
  2554. if (targetProperties.webworker) conditions.push("worker");
  2555. if (targetProperties.node) conditions.push("node");
  2556. if (targetProperties.web) conditions.push("browser");
  2557. if (targetProperties.electron) conditions.push("electron");
  2558. if (targetProperties.nwjs) conditions.push("nwjs");
  2559. }
  2560. const jsExtensions = typescript
  2561. ? [".ts", ".js", ".json", ".wasm"]
  2562. : [".js", ".json", ".wasm"];
  2563. // Explicitly enabling html keeps `.html` ahead of `.js` (html-as-entry feature).
  2564. // Auto-enabled html/css are lower-priority fallbacks after `.js`, so enabling
  2565. // them by default never makes `x.html`/`x.css` shadow `x.js`.
  2566. const esmResolveExtensions = [
  2567. ...(html && htmlFirst ? [".html"] : []),
  2568. ...jsExtensions,
  2569. ...(html && !htmlFirst ? [".html"] : []),
  2570. ...(css ? [".css"] : [])
  2571. ];
  2572. const tp = targetProperties;
  2573. const browserField =
  2574. tp && tp.web && (!tp.node || (tp.electron && tp.electronRenderer));
  2575. // When `experiments.typescript` is on, also honor the `typescript`
  2576. // conditional-exports key so monorepo packages can ship .ts sources via
  2577. // `package.json#exports` — same convention Node.js's amaro uses.
  2578. const tsConditionPrefix = typescript ? ["typescript"] : [];
  2579. /** @type {() => ResolveOptions} */
  2580. const cjsDeps = () => ({
  2581. aliasFields: browserField ? ["browser"] : [],
  2582. mainFields: browserField ? ["browser", "module", "..."] : ["module", "..."],
  2583. conditionNames: [
  2584. ...tsConditionPrefix,
  2585. "require",
  2586. "module-sync",
  2587. "module",
  2588. "..."
  2589. ],
  2590. extensions: [...jsExtensions]
  2591. });
  2592. /** @type {() => ResolveOptions} */
  2593. const esmDeps = () => ({
  2594. aliasFields: browserField ? ["browser"] : [],
  2595. mainFields: browserField ? ["browser", "module", "..."] : ["module", "..."],
  2596. conditionNames: [
  2597. ...tsConditionPrefix,
  2598. "import",
  2599. "module-sync",
  2600. "module",
  2601. "..."
  2602. ],
  2603. extensions: [...esmResolveExtensions]
  2604. });
  2605. /** @type {() => ResolveOptions} */
  2606. const workerDeps = () => {
  2607. const options = esmDeps();
  2608. const conditionNames = options.conditionNames
  2609. ? ["worker", ...options.conditionNames]
  2610. : options.conditionNames;
  2611. return {
  2612. ...options,
  2613. conditionNames,
  2614. preferRelative: true
  2615. };
  2616. };
  2617. /** @type {ResolveOptions} */
  2618. const resolveOptions = {
  2619. cache,
  2620. modules: ["node_modules"],
  2621. conditionNames: conditions,
  2622. mainFiles: ["index"],
  2623. extensions: [],
  2624. aliasFields: [],
  2625. exportsFields: ["exports"],
  2626. roots: [context],
  2627. mainFields: ["main"],
  2628. importsFields: ["imports"],
  2629. byDependency: {
  2630. wasm: esmDeps(),
  2631. esm: esmDeps(),
  2632. loaderImport: esmDeps(),
  2633. url: {
  2634. preferRelative: true
  2635. },
  2636. worker: workerDeps(),
  2637. commonjs: cjsDeps(),
  2638. amd: cjsDeps(),
  2639. // for backward-compat: loadModule
  2640. loader: cjsDeps(),
  2641. // for backward-compat: Custom Dependency
  2642. unknown: cjsDeps(),
  2643. // for backward-compat: getResolve without dependencyType
  2644. undefined: cjsDeps()
  2645. }
  2646. };
  2647. if (css) {
  2648. /** @type {string[]} */
  2649. const styleConditions = [];
  2650. styleConditions.push("webpack");
  2651. styleConditions.push(mode === "development" ? "development" : "production");
  2652. styleConditions.push("style");
  2653. /** @type {ResolveOptions} */
  2654. const cssResolveOptions = {
  2655. // We avoid using any main files because we have to be consistent with CSS `@import`
  2656. // and CSS `@import` does not handle `main` files in directories,
  2657. // you should always specify the full URL for styles
  2658. mainFiles: [],
  2659. mainFields: ["style", "..."],
  2660. conditionNames: styleConditions,
  2661. extensions: [".css"],
  2662. preferRelative: true
  2663. };
  2664. /** @type {NonNullable<ResolveOptions["byDependency"]>} */
  2665. (resolveOptions.byDependency)["css-import"] = cssResolveOptions;
  2666. // For CSS modules, i.e. `.class { composes: className from "./style.css" }`
  2667. // We inherit for such constructions
  2668. /** @type {NonNullable<ResolveOptions["byDependency"]>} */
  2669. (resolveOptions.byDependency)["css-import-local-module"] =
  2670. cssResolveOptions;
  2671. /** @type {NonNullable<ResolveOptions["byDependency"]>} */
  2672. (resolveOptions.byDependency)["css-import-global-module"] =
  2673. cssResolveOptions;
  2674. }
  2675. if (typescript) {
  2676. resolveOptions.tsconfig = true;
  2677. resolveOptions.extensionAlias = {
  2678. ".js": [".js", ".ts"],
  2679. ".cjs": [".cjs", ".cts"],
  2680. ".mjs": [".mjs", ".mts"]
  2681. };
  2682. }
  2683. return resolveOptions;
  2684. };
  2685. /**
  2686. * Gets resolve loader defaults.
  2687. * @param {object} options options
  2688. * @param {boolean} options.cache is cache enable
  2689. * @returns {ResolveOptions} resolve options
  2690. */
  2691. const getResolveLoaderDefaults = ({ cache }) => {
  2692. /** @type {ResolveOptions} */
  2693. const resolveOptions = {
  2694. cache,
  2695. conditionNames: ["loader", "require", "node"],
  2696. exportsFields: ["exports"],
  2697. mainFields: ["loader", "main"],
  2698. extensions: [".js"],
  2699. mainFiles: ["index"]
  2700. };
  2701. return resolveOptions;
  2702. };
  2703. /**
  2704. * Apply infrastructure logging defaults.
  2705. * @param {InfrastructureLogging} infrastructureLogging options
  2706. * @returns {void}
  2707. */
  2708. const applyInfrastructureLoggingDefaults = (infrastructureLogging) => {
  2709. F(infrastructureLogging, "stream", () => process.stderr);
  2710. const tty =
  2711. /** @type {NonNullable<InfrastructureLogging["stream"]>} */
  2712. (infrastructureLogging.stream).isTTY && process.env.TERM !== "dumb";
  2713. D(infrastructureLogging, "level", "info");
  2714. D(infrastructureLogging, "debug", false);
  2715. D(infrastructureLogging, "colors", tty);
  2716. D(infrastructureLogging, "appendOnly", !tty);
  2717. };
  2718. module.exports.DEFAULTS = DEFAULTS;
  2719. module.exports.applyWebpackOptionsBaseDefaults =
  2720. applyWebpackOptionsBaseDefaults;
  2721. module.exports.applyWebpackOptionsDefaults = applyWebpackOptionsDefaults;