defaults.js 64 KB

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