SplitChunksPlugin.js 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const Chunk = require("../Chunk");
  7. const { STAGE_ADVANCED } = require("../OptimizationStages");
  8. const WebpackError = require("../WebpackError");
  9. const { requestToId } = require("../ids/IdHelpers");
  10. const { isSubset } = require("../util/SetHelpers");
  11. const SortableSet = require("../util/SortableSet");
  12. const {
  13. compareModulesByIdentifier,
  14. compareIterables
  15. } = require("../util/comparators");
  16. const createHash = require("../util/createHash");
  17. const deterministicGrouping = require("../util/deterministicGrouping");
  18. const { makePathsRelative } = require("../util/identifier");
  19. const memoize = require("../util/memoize");
  20. const MinMaxSizeWarning = require("./MinMaxSizeWarning");
  21. /** @typedef {import("../../declarations/WebpackOptions").OptimizationSplitChunksCacheGroup} OptimizationSplitChunksCacheGroup */
  22. /** @typedef {import("../../declarations/WebpackOptions").OptimizationSplitChunksGetCacheGroups} OptimizationSplitChunksGetCacheGroups */
  23. /** @typedef {import("../../declarations/WebpackOptions").OptimizationSplitChunksOptions} OptimizationSplitChunksOptions */
  24. /** @typedef {import("../../declarations/WebpackOptions").OptimizationSplitChunksSizes} OptimizationSplitChunksSizes */
  25. /** @typedef {import("../../declarations/WebpackOptions").Output} OutputOptions */
  26. /** @typedef {import("../ChunkGraph")} ChunkGraph */
  27. /** @typedef {import("../ChunkGroup")} ChunkGroup */
  28. /** @typedef {import("../Compiler")} Compiler */
  29. /** @typedef {import("../Module")} Module */
  30. /** @typedef {import("../ModuleGraph")} ModuleGraph */
  31. /** @typedef {import("../TemplatedPathPlugin").TemplatePath} TemplatePath */
  32. /** @typedef {import("../util/createHash").Algorithm} Algorithm */
  33. /** @typedef {import("../util/deterministicGrouping").GroupedItems<Module>} DeterministicGroupingGroupedItemsForModule */
  34. /** @typedef {import("../util/deterministicGrouping").Options<Module>} DeterministicGroupingOptionsForModule */
  35. /** @typedef {Record<string, number>} SplitChunksSizes */
  36. /**
  37. * @callback ChunkFilterFunction
  38. * @param {Chunk} chunk
  39. * @returns {boolean | undefined}
  40. */
  41. /**
  42. * @callback CombineSizeFunction
  43. * @param {number} a
  44. * @param {number} b
  45. * @returns {number}
  46. */
  47. /**
  48. * @typedef {object} CacheGroupSource
  49. * @property {string} key
  50. * @property {number=} priority
  51. * @property {GetName=} getName
  52. * @property {ChunkFilterFunction=} chunksFilter
  53. * @property {boolean=} enforce
  54. * @property {SplitChunksSizes} minSize
  55. * @property {SplitChunksSizes} minSizeReduction
  56. * @property {SplitChunksSizes} minRemainingSize
  57. * @property {SplitChunksSizes} enforceSizeThreshold
  58. * @property {SplitChunksSizes} maxAsyncSize
  59. * @property {SplitChunksSizes} maxInitialSize
  60. * @property {number=} minChunks
  61. * @property {number=} maxAsyncRequests
  62. * @property {number=} maxInitialRequests
  63. * @property {TemplatePath=} filename
  64. * @property {string=} idHint
  65. * @property {string=} automaticNameDelimiter
  66. * @property {boolean=} reuseExistingChunk
  67. * @property {boolean=} usedExports
  68. */
  69. /**
  70. * @typedef {object} CacheGroup
  71. * @property {string} key
  72. * @property {number} priority
  73. * @property {GetName=} getName
  74. * @property {ChunkFilterFunction} chunksFilter
  75. * @property {SplitChunksSizes} minSize
  76. * @property {SplitChunksSizes} minSizeReduction
  77. * @property {SplitChunksSizes} minRemainingSize
  78. * @property {SplitChunksSizes} enforceSizeThreshold
  79. * @property {SplitChunksSizes} maxAsyncSize
  80. * @property {SplitChunksSizes} maxInitialSize
  81. * @property {number} minChunks
  82. * @property {number} maxAsyncRequests
  83. * @property {number} maxInitialRequests
  84. * @property {TemplatePath=} filename
  85. * @property {string} idHint
  86. * @property {string} automaticNameDelimiter
  87. * @property {boolean} reuseExistingChunk
  88. * @property {boolean} usedExports
  89. * @property {boolean} _validateSize
  90. * @property {boolean} _validateRemainingSize
  91. * @property {SplitChunksSizes} _minSizeForMaxSize
  92. * @property {boolean} _conditionalEnforce
  93. */
  94. /**
  95. * @typedef {object} FallbackCacheGroup
  96. * @property {ChunkFilterFunction} chunksFilter
  97. * @property {SplitChunksSizes} minSize
  98. * @property {SplitChunksSizes} maxAsyncSize
  99. * @property {SplitChunksSizes} maxInitialSize
  100. * @property {string} automaticNameDelimiter
  101. */
  102. /**
  103. * @typedef {object} CacheGroupsContext
  104. * @property {ModuleGraph} moduleGraph
  105. * @property {ChunkGraph} chunkGraph
  106. */
  107. /**
  108. * @callback GetCacheGroups
  109. * @param {Module} module
  110. * @param {CacheGroupsContext} context
  111. * @returns {CacheGroupSource[] | null}
  112. */
  113. /**
  114. * @callback GetName
  115. * @param {Module} module
  116. * @param {Chunk[]} chunks
  117. * @param {string} key
  118. * @returns {string=}
  119. */
  120. /**
  121. * @typedef {object} SplitChunksOptions
  122. * @property {ChunkFilterFunction} chunksFilter
  123. * @property {string[]} defaultSizeTypes
  124. * @property {SplitChunksSizes} minSize
  125. * @property {SplitChunksSizes} minSizeReduction
  126. * @property {SplitChunksSizes} minRemainingSize
  127. * @property {SplitChunksSizes} enforceSizeThreshold
  128. * @property {SplitChunksSizes} maxInitialSize
  129. * @property {SplitChunksSizes} maxAsyncSize
  130. * @property {number} minChunks
  131. * @property {number} maxAsyncRequests
  132. * @property {number} maxInitialRequests
  133. * @property {boolean} hidePathInfo
  134. * @property {TemplatePath=} filename
  135. * @property {string} automaticNameDelimiter
  136. * @property {GetCacheGroups} getCacheGroups
  137. * @property {GetName} getName
  138. * @property {boolean} usedExports
  139. * @property {FallbackCacheGroup} fallbackCacheGroup
  140. */
  141. /**
  142. * @typedef {object} ChunksInfoItem
  143. * @property {SortableSet<Module>} modules
  144. * @property {CacheGroup} cacheGroup
  145. * @property {number} cacheGroupIndex
  146. * @property {string=} name
  147. * @property {Record<string, number>} sizes
  148. * @property {Set<Chunk>} chunks
  149. * @property {Set<Chunk>} reusableChunks
  150. * @property {Set<bigint | Chunk>} chunksKeys
  151. */
  152. /** @type {GetName} */
  153. const defaultGetName = () => undefined;
  154. const deterministicGroupingForModules =
  155. /** @type {(options: DeterministicGroupingOptionsForModule) => DeterministicGroupingGroupedItemsForModule[]} */
  156. (deterministicGrouping);
  157. /** @type {WeakMap<Module, string>} */
  158. const getKeyCache = new WeakMap();
  159. /**
  160. * @param {string} name a filename to hash
  161. * @param {OutputOptions} outputOptions hash function used
  162. * @returns {string} hashed filename
  163. */
  164. const hashFilename = (name, outputOptions) => {
  165. const digest =
  166. /** @type {string} */
  167. (
  168. createHash(/** @type {Algorithm} */ (outputOptions.hashFunction))
  169. .update(name)
  170. .digest(outputOptions.hashDigest)
  171. );
  172. return digest.slice(0, 8);
  173. };
  174. /**
  175. * @param {Chunk} chunk the chunk
  176. * @returns {number} the number of requests
  177. */
  178. const getRequests = chunk => {
  179. let requests = 0;
  180. for (const chunkGroup of chunk.groupsIterable) {
  181. requests = Math.max(requests, chunkGroup.chunks.length);
  182. }
  183. return requests;
  184. };
  185. /**
  186. * @template {object} T
  187. * @template {object} R
  188. * @param {T} obj obj an object
  189. * @param {function(T[keyof T], keyof T): T[keyof T]} fn fn
  190. * @returns {T} result
  191. */
  192. const mapObject = (obj, fn) => {
  193. const newObj = Object.create(null);
  194. for (const key of Object.keys(obj)) {
  195. newObj[key] = fn(
  196. obj[/** @type {keyof T} */ (key)],
  197. /** @type {keyof T} */
  198. (key)
  199. );
  200. }
  201. return newObj;
  202. };
  203. /**
  204. * @template T
  205. * @param {Set<T>} a set
  206. * @param {Set<T>} b other set
  207. * @returns {boolean} true if at least one item of a is in b
  208. */
  209. const isOverlap = (a, b) => {
  210. for (const item of a) {
  211. if (b.has(item)) return true;
  212. }
  213. return false;
  214. };
  215. const compareModuleIterables = compareIterables(compareModulesByIdentifier);
  216. /**
  217. * @param {ChunksInfoItem} a item
  218. * @param {ChunksInfoItem} b item
  219. * @returns {number} compare result
  220. */
  221. const compareEntries = (a, b) => {
  222. // 1. by priority
  223. const diffPriority = a.cacheGroup.priority - b.cacheGroup.priority;
  224. if (diffPriority) return diffPriority;
  225. // 2. by number of chunks
  226. const diffCount = a.chunks.size - b.chunks.size;
  227. if (diffCount) return diffCount;
  228. // 3. by size reduction
  229. const aSizeReduce = totalSize(a.sizes) * (a.chunks.size - 1);
  230. const bSizeReduce = totalSize(b.sizes) * (b.chunks.size - 1);
  231. const diffSizeReduce = aSizeReduce - bSizeReduce;
  232. if (diffSizeReduce) return diffSizeReduce;
  233. // 4. by cache group index
  234. const indexDiff = b.cacheGroupIndex - a.cacheGroupIndex;
  235. if (indexDiff) return indexDiff;
  236. // 5. by number of modules (to be able to compare by identifier)
  237. const modulesA = a.modules;
  238. const modulesB = b.modules;
  239. const diff = modulesA.size - modulesB.size;
  240. if (diff) return diff;
  241. // 6. by module identifiers
  242. modulesA.sort();
  243. modulesB.sort();
  244. return compareModuleIterables(modulesA, modulesB);
  245. };
  246. /**
  247. * @param {Chunk} chunk the chunk
  248. * @returns {boolean} true, if the chunk is an entry chunk
  249. */
  250. const INITIAL_CHUNK_FILTER = chunk => chunk.canBeInitial();
  251. /**
  252. * @param {Chunk} chunk the chunk
  253. * @returns {boolean} true, if the chunk is an async chunk
  254. */
  255. const ASYNC_CHUNK_FILTER = chunk => !chunk.canBeInitial();
  256. /**
  257. * @param {Chunk} chunk the chunk
  258. * @returns {boolean} always true
  259. */
  260. const ALL_CHUNK_FILTER = chunk => true;
  261. /**
  262. * @param {OptimizationSplitChunksSizes | undefined} value the sizes
  263. * @param {string[]} defaultSizeTypes the default size types
  264. * @returns {SplitChunksSizes} normalized representation
  265. */
  266. const normalizeSizes = (value, defaultSizeTypes) => {
  267. if (typeof value === "number") {
  268. /** @type {Record<string, number>} */
  269. const o = {};
  270. for (const sizeType of defaultSizeTypes) o[sizeType] = value;
  271. return o;
  272. } else if (typeof value === "object" && value !== null) {
  273. return { ...value };
  274. }
  275. return {};
  276. };
  277. /**
  278. * @param {...(SplitChunksSizes | undefined)} sizes the sizes
  279. * @returns {SplitChunksSizes} the merged sizes
  280. */
  281. const mergeSizes = (...sizes) => {
  282. /** @type {SplitChunksSizes} */
  283. let merged = {};
  284. for (let i = sizes.length - 1; i >= 0; i--) {
  285. merged = Object.assign(merged, sizes[i]);
  286. }
  287. return merged;
  288. };
  289. /**
  290. * @param {SplitChunksSizes} sizes the sizes
  291. * @returns {boolean} true, if there are sizes > 0
  292. */
  293. const hasNonZeroSizes = sizes => {
  294. for (const key of Object.keys(sizes)) {
  295. if (sizes[key] > 0) return true;
  296. }
  297. return false;
  298. };
  299. /**
  300. * @param {SplitChunksSizes} a first sizes
  301. * @param {SplitChunksSizes} b second sizes
  302. * @param {CombineSizeFunction} combine a function to combine sizes
  303. * @returns {SplitChunksSizes} the combine sizes
  304. */
  305. const combineSizes = (a, b, combine) => {
  306. const aKeys = new Set(Object.keys(a));
  307. const bKeys = new Set(Object.keys(b));
  308. /** @type {SplitChunksSizes} */
  309. const result = {};
  310. for (const key of aKeys) {
  311. result[key] = bKeys.has(key) ? combine(a[key], b[key]) : a[key];
  312. }
  313. for (const key of bKeys) {
  314. if (!aKeys.has(key)) {
  315. result[key] = b[key];
  316. }
  317. }
  318. return result;
  319. };
  320. /**
  321. * @param {SplitChunksSizes} sizes the sizes
  322. * @param {SplitChunksSizes} minSize the min sizes
  323. * @returns {boolean} true if there are sizes and all existing sizes are at least `minSize`
  324. */
  325. const checkMinSize = (sizes, minSize) => {
  326. for (const key of Object.keys(minSize)) {
  327. const size = sizes[key];
  328. if (size === undefined || size === 0) continue;
  329. if (size < minSize[key]) return false;
  330. }
  331. return true;
  332. };
  333. /**
  334. * @param {SplitChunksSizes} sizes the sizes
  335. * @param {SplitChunksSizes} minSizeReduction the min sizes
  336. * @param {number} chunkCount number of chunks
  337. * @returns {boolean} true if there are sizes and all existing sizes are at least `minSizeReduction`
  338. */
  339. const checkMinSizeReduction = (sizes, minSizeReduction, chunkCount) => {
  340. for (const key of Object.keys(minSizeReduction)) {
  341. const size = sizes[key];
  342. if (size === undefined || size === 0) continue;
  343. if (size * chunkCount < minSizeReduction[key]) return false;
  344. }
  345. return true;
  346. };
  347. /**
  348. * @param {SplitChunksSizes} sizes the sizes
  349. * @param {SplitChunksSizes} minSize the min sizes
  350. * @returns {undefined | string[]} list of size types that are below min size
  351. */
  352. const getViolatingMinSizes = (sizes, minSize) => {
  353. let list;
  354. for (const key of Object.keys(minSize)) {
  355. const size = sizes[key];
  356. if (size === undefined || size === 0) continue;
  357. if (size < minSize[key]) {
  358. if (list === undefined) list = [key];
  359. else list.push(key);
  360. }
  361. }
  362. return list;
  363. };
  364. /**
  365. * @param {SplitChunksSizes} sizes the sizes
  366. * @returns {number} the total size
  367. */
  368. const totalSize = sizes => {
  369. let size = 0;
  370. for (const key of Object.keys(sizes)) {
  371. size += sizes[key];
  372. }
  373. return size;
  374. };
  375. /**
  376. * @param {OptimizationSplitChunksCacheGroup["name"]} name the chunk name
  377. * @returns {GetName | undefined} a function to get the name of the chunk
  378. */
  379. const normalizeName = name => {
  380. if (typeof name === "string") {
  381. return () => name;
  382. }
  383. if (typeof name === "function") {
  384. return /** @type {GetName} */ (name);
  385. }
  386. };
  387. /**
  388. * @param {OptimizationSplitChunksCacheGroup["chunks"]} chunks the chunk filter option
  389. * @returns {ChunkFilterFunction | undefined} the chunk filter function
  390. */
  391. const normalizeChunksFilter = chunks => {
  392. if (chunks === "initial") {
  393. return INITIAL_CHUNK_FILTER;
  394. }
  395. if (chunks === "async") {
  396. return ASYNC_CHUNK_FILTER;
  397. }
  398. if (chunks === "all") {
  399. return ALL_CHUNK_FILTER;
  400. }
  401. if (chunks instanceof RegExp) {
  402. return chunk => (chunk.name ? chunks.test(chunk.name) : false);
  403. }
  404. if (typeof chunks === "function") {
  405. return chunks;
  406. }
  407. };
  408. /**
  409. * @param {undefined | GetCacheGroups | Record<string, false | string | RegExp | OptimizationSplitChunksGetCacheGroups | OptimizationSplitChunksCacheGroup>} cacheGroups the cache group options
  410. * @param {string[]} defaultSizeTypes the default size types
  411. * @returns {GetCacheGroups} a function to get the cache groups
  412. */
  413. const normalizeCacheGroups = (cacheGroups, defaultSizeTypes) => {
  414. if (typeof cacheGroups === "function") {
  415. return cacheGroups;
  416. }
  417. if (typeof cacheGroups === "object" && cacheGroups !== null) {
  418. /** @type {((module: Module, context: CacheGroupsContext, results: CacheGroupSource[]) => void)[]} */
  419. const handlers = [];
  420. for (const key of Object.keys(cacheGroups)) {
  421. const option = cacheGroups[key];
  422. if (option === false) {
  423. continue;
  424. }
  425. if (typeof option === "string" || option instanceof RegExp) {
  426. const source = createCacheGroupSource({}, key, defaultSizeTypes);
  427. handlers.push((module, context, results) => {
  428. if (checkTest(option, module, context)) {
  429. results.push(source);
  430. }
  431. });
  432. } else if (typeof option === "function") {
  433. const cache = new WeakMap();
  434. handlers.push((module, context, results) => {
  435. const result = option(module);
  436. if (result) {
  437. const groups = Array.isArray(result) ? result : [result];
  438. for (const group of groups) {
  439. const cachedSource = cache.get(group);
  440. if (cachedSource !== undefined) {
  441. results.push(cachedSource);
  442. } else {
  443. const source = createCacheGroupSource(
  444. group,
  445. key,
  446. defaultSizeTypes
  447. );
  448. cache.set(group, source);
  449. results.push(source);
  450. }
  451. }
  452. }
  453. });
  454. } else {
  455. const source = createCacheGroupSource(option, key, defaultSizeTypes);
  456. handlers.push((module, context, results) => {
  457. if (
  458. checkTest(option.test, module, context) &&
  459. checkModuleType(option.type, module) &&
  460. checkModuleLayer(option.layer, module)
  461. ) {
  462. results.push(source);
  463. }
  464. });
  465. }
  466. }
  467. /**
  468. * @param {Module} module the current module
  469. * @param {CacheGroupsContext} context the current context
  470. * @returns {CacheGroupSource[]} the matching cache groups
  471. */
  472. const fn = (module, context) => {
  473. /** @type {CacheGroupSource[]} */
  474. const results = [];
  475. for (const fn of handlers) {
  476. fn(module, context, results);
  477. }
  478. return results;
  479. };
  480. return fn;
  481. }
  482. return () => null;
  483. };
  484. /**
  485. * @param {OptimizationSplitChunksCacheGroup["test"]} test test option
  486. * @param {Module} module the module
  487. * @param {CacheGroupsContext} context context object
  488. * @returns {boolean} true, if the module should be selected
  489. */
  490. const checkTest = (test, module, context) => {
  491. if (test === undefined) return true;
  492. if (typeof test === "function") {
  493. return test(module, context);
  494. }
  495. if (typeof test === "boolean") return test;
  496. if (typeof test === "string") {
  497. const name = module.nameForCondition();
  498. return name ? name.startsWith(test) : false;
  499. }
  500. if (test instanceof RegExp) {
  501. const name = module.nameForCondition();
  502. return name ? test.test(name) : false;
  503. }
  504. return false;
  505. };
  506. /**
  507. * @param {OptimizationSplitChunksCacheGroup["type"]} test type option
  508. * @param {Module} module the module
  509. * @returns {boolean} true, if the module should be selected
  510. */
  511. const checkModuleType = (test, module) => {
  512. if (test === undefined) return true;
  513. if (typeof test === "function") {
  514. return test(module.type);
  515. }
  516. if (typeof test === "string") {
  517. const type = module.type;
  518. return test === type;
  519. }
  520. if (test instanceof RegExp) {
  521. const type = module.type;
  522. return test.test(type);
  523. }
  524. return false;
  525. };
  526. /**
  527. * @param {OptimizationSplitChunksCacheGroup["layer"]} test type option
  528. * @param {Module} module the module
  529. * @returns {boolean} true, if the module should be selected
  530. */
  531. const checkModuleLayer = (test, module) => {
  532. if (test === undefined) return true;
  533. if (typeof test === "function") {
  534. return test(module.layer);
  535. }
  536. if (typeof test === "string") {
  537. const layer = module.layer;
  538. return test === "" ? !layer : layer ? layer.startsWith(test) : false;
  539. }
  540. if (test instanceof RegExp) {
  541. const layer = module.layer;
  542. return layer ? test.test(layer) : false;
  543. }
  544. return false;
  545. };
  546. /**
  547. * @param {OptimizationSplitChunksCacheGroup} options the group options
  548. * @param {string} key key of cache group
  549. * @param {string[]} defaultSizeTypes the default size types
  550. * @returns {CacheGroupSource} the normalized cached group
  551. */
  552. const createCacheGroupSource = (options, key, defaultSizeTypes) => {
  553. const minSize = normalizeSizes(options.minSize, defaultSizeTypes);
  554. const minSizeReduction = normalizeSizes(
  555. options.minSizeReduction,
  556. defaultSizeTypes
  557. );
  558. const maxSize = normalizeSizes(options.maxSize, defaultSizeTypes);
  559. return {
  560. key,
  561. priority: options.priority,
  562. getName: normalizeName(options.name),
  563. chunksFilter: normalizeChunksFilter(options.chunks),
  564. enforce: options.enforce,
  565. minSize,
  566. minSizeReduction,
  567. minRemainingSize: mergeSizes(
  568. normalizeSizes(options.minRemainingSize, defaultSizeTypes),
  569. minSize
  570. ),
  571. enforceSizeThreshold: normalizeSizes(
  572. options.enforceSizeThreshold,
  573. defaultSizeTypes
  574. ),
  575. maxAsyncSize: mergeSizes(
  576. normalizeSizes(options.maxAsyncSize, defaultSizeTypes),
  577. maxSize
  578. ),
  579. maxInitialSize: mergeSizes(
  580. normalizeSizes(options.maxInitialSize, defaultSizeTypes),
  581. maxSize
  582. ),
  583. minChunks: options.minChunks,
  584. maxAsyncRequests: options.maxAsyncRequests,
  585. maxInitialRequests: options.maxInitialRequests,
  586. filename: options.filename,
  587. idHint: options.idHint,
  588. automaticNameDelimiter: options.automaticNameDelimiter,
  589. reuseExistingChunk: options.reuseExistingChunk,
  590. usedExports: options.usedExports
  591. };
  592. };
  593. module.exports = class SplitChunksPlugin {
  594. /**
  595. * @param {OptimizationSplitChunksOptions=} options plugin options
  596. */
  597. constructor(options = {}) {
  598. const defaultSizeTypes = options.defaultSizeTypes || [
  599. "javascript",
  600. "unknown"
  601. ];
  602. const fallbackCacheGroup = options.fallbackCacheGroup || {};
  603. const minSize = normalizeSizes(options.minSize, defaultSizeTypes);
  604. const minSizeReduction = normalizeSizes(
  605. options.minSizeReduction,
  606. defaultSizeTypes
  607. );
  608. const maxSize = normalizeSizes(options.maxSize, defaultSizeTypes);
  609. /** @type {SplitChunksOptions} */
  610. this.options = {
  611. chunksFilter:
  612. /** @type {ChunkFilterFunction} */
  613. (normalizeChunksFilter(options.chunks || "all")),
  614. defaultSizeTypes,
  615. minSize,
  616. minSizeReduction,
  617. minRemainingSize: mergeSizes(
  618. normalizeSizes(options.minRemainingSize, defaultSizeTypes),
  619. minSize
  620. ),
  621. enforceSizeThreshold: normalizeSizes(
  622. options.enforceSizeThreshold,
  623. defaultSizeTypes
  624. ),
  625. maxAsyncSize: mergeSizes(
  626. normalizeSizes(options.maxAsyncSize, defaultSizeTypes),
  627. maxSize
  628. ),
  629. maxInitialSize: mergeSizes(
  630. normalizeSizes(options.maxInitialSize, defaultSizeTypes),
  631. maxSize
  632. ),
  633. minChunks: options.minChunks || 1,
  634. maxAsyncRequests: options.maxAsyncRequests || 1,
  635. maxInitialRequests: options.maxInitialRequests || 1,
  636. hidePathInfo: options.hidePathInfo || false,
  637. filename: options.filename || undefined,
  638. getCacheGroups: normalizeCacheGroups(
  639. options.cacheGroups,
  640. defaultSizeTypes
  641. ),
  642. getName: options.name
  643. ? /** @type {GetName} */ (normalizeName(options.name))
  644. : defaultGetName,
  645. automaticNameDelimiter: options.automaticNameDelimiter || "-",
  646. usedExports: options.usedExports || false,
  647. fallbackCacheGroup: {
  648. chunksFilter:
  649. /** @type {ChunkFilterFunction} */
  650. (
  651. normalizeChunksFilter(
  652. fallbackCacheGroup.chunks || options.chunks || "all"
  653. )
  654. ),
  655. minSize: mergeSizes(
  656. normalizeSizes(fallbackCacheGroup.minSize, defaultSizeTypes),
  657. minSize
  658. ),
  659. maxAsyncSize: mergeSizes(
  660. normalizeSizes(fallbackCacheGroup.maxAsyncSize, defaultSizeTypes),
  661. normalizeSizes(fallbackCacheGroup.maxSize, defaultSizeTypes),
  662. normalizeSizes(options.maxAsyncSize, defaultSizeTypes),
  663. normalizeSizes(options.maxSize, defaultSizeTypes)
  664. ),
  665. maxInitialSize: mergeSizes(
  666. normalizeSizes(fallbackCacheGroup.maxInitialSize, defaultSizeTypes),
  667. normalizeSizes(fallbackCacheGroup.maxSize, defaultSizeTypes),
  668. normalizeSizes(options.maxInitialSize, defaultSizeTypes),
  669. normalizeSizes(options.maxSize, defaultSizeTypes)
  670. ),
  671. automaticNameDelimiter:
  672. fallbackCacheGroup.automaticNameDelimiter ||
  673. options.automaticNameDelimiter ||
  674. "~"
  675. }
  676. };
  677. /** @type {WeakMap<CacheGroupSource, CacheGroup>} */
  678. this._cacheGroupCache = new WeakMap();
  679. }
  680. /**
  681. * @param {CacheGroupSource} cacheGroupSource source
  682. * @returns {CacheGroup} the cache group (cached)
  683. */
  684. _getCacheGroup(cacheGroupSource) {
  685. const cacheEntry = this._cacheGroupCache.get(cacheGroupSource);
  686. if (cacheEntry !== undefined) return cacheEntry;
  687. const minSize = mergeSizes(
  688. cacheGroupSource.minSize,
  689. cacheGroupSource.enforce ? undefined : this.options.minSize
  690. );
  691. const minSizeReduction = mergeSizes(
  692. cacheGroupSource.minSizeReduction,
  693. cacheGroupSource.enforce ? undefined : this.options.minSizeReduction
  694. );
  695. const minRemainingSize = mergeSizes(
  696. cacheGroupSource.minRemainingSize,
  697. cacheGroupSource.enforce ? undefined : this.options.minRemainingSize
  698. );
  699. const enforceSizeThreshold = mergeSizes(
  700. cacheGroupSource.enforceSizeThreshold,
  701. cacheGroupSource.enforce ? undefined : this.options.enforceSizeThreshold
  702. );
  703. /** @type {CacheGroup} */
  704. const cacheGroup = {
  705. key: cacheGroupSource.key,
  706. priority: cacheGroupSource.priority || 0,
  707. chunksFilter: cacheGroupSource.chunksFilter || this.options.chunksFilter,
  708. minSize,
  709. minSizeReduction,
  710. minRemainingSize,
  711. enforceSizeThreshold,
  712. maxAsyncSize: mergeSizes(
  713. cacheGroupSource.maxAsyncSize,
  714. cacheGroupSource.enforce ? undefined : this.options.maxAsyncSize
  715. ),
  716. maxInitialSize: mergeSizes(
  717. cacheGroupSource.maxInitialSize,
  718. cacheGroupSource.enforce ? undefined : this.options.maxInitialSize
  719. ),
  720. minChunks:
  721. cacheGroupSource.minChunks !== undefined
  722. ? cacheGroupSource.minChunks
  723. : cacheGroupSource.enforce
  724. ? 1
  725. : this.options.minChunks,
  726. maxAsyncRequests:
  727. cacheGroupSource.maxAsyncRequests !== undefined
  728. ? cacheGroupSource.maxAsyncRequests
  729. : cacheGroupSource.enforce
  730. ? Infinity
  731. : this.options.maxAsyncRequests,
  732. maxInitialRequests:
  733. cacheGroupSource.maxInitialRequests !== undefined
  734. ? cacheGroupSource.maxInitialRequests
  735. : cacheGroupSource.enforce
  736. ? Infinity
  737. : this.options.maxInitialRequests,
  738. getName:
  739. cacheGroupSource.getName !== undefined
  740. ? cacheGroupSource.getName
  741. : this.options.getName,
  742. usedExports:
  743. cacheGroupSource.usedExports !== undefined
  744. ? cacheGroupSource.usedExports
  745. : this.options.usedExports,
  746. filename:
  747. cacheGroupSource.filename !== undefined
  748. ? cacheGroupSource.filename
  749. : this.options.filename,
  750. automaticNameDelimiter:
  751. cacheGroupSource.automaticNameDelimiter !== undefined
  752. ? cacheGroupSource.automaticNameDelimiter
  753. : this.options.automaticNameDelimiter,
  754. idHint:
  755. cacheGroupSource.idHint !== undefined
  756. ? cacheGroupSource.idHint
  757. : cacheGroupSource.key,
  758. reuseExistingChunk: cacheGroupSource.reuseExistingChunk || false,
  759. _validateSize: hasNonZeroSizes(minSize),
  760. _validateRemainingSize: hasNonZeroSizes(minRemainingSize),
  761. _minSizeForMaxSize: mergeSizes(
  762. cacheGroupSource.minSize,
  763. this.options.minSize
  764. ),
  765. _conditionalEnforce: hasNonZeroSizes(enforceSizeThreshold)
  766. };
  767. this._cacheGroupCache.set(cacheGroupSource, cacheGroup);
  768. return cacheGroup;
  769. }
  770. /**
  771. * Apply the plugin
  772. * @param {Compiler} compiler the compiler instance
  773. * @returns {void}
  774. */
  775. apply(compiler) {
  776. const cachedMakePathsRelative = makePathsRelative.bindContextCache(
  777. compiler.context,
  778. compiler.root
  779. );
  780. compiler.hooks.thisCompilation.tap("SplitChunksPlugin", compilation => {
  781. const logger = compilation.getLogger("webpack.SplitChunksPlugin");
  782. let alreadyOptimized = false;
  783. compilation.hooks.unseal.tap("SplitChunksPlugin", () => {
  784. alreadyOptimized = false;
  785. });
  786. compilation.hooks.optimizeChunks.tap(
  787. {
  788. name: "SplitChunksPlugin",
  789. stage: STAGE_ADVANCED
  790. },
  791. chunks => {
  792. if (alreadyOptimized) return;
  793. alreadyOptimized = true;
  794. logger.time("prepare");
  795. const chunkGraph = compilation.chunkGraph;
  796. const moduleGraph = compilation.moduleGraph;
  797. // Give each selected chunk an index (to create strings from chunks)
  798. /** @type {Map<Chunk, bigint>} */
  799. const chunkIndexMap = new Map();
  800. const ZERO = BigInt("0");
  801. const ONE = BigInt("1");
  802. const START = ONE << BigInt("31");
  803. let index = START;
  804. for (const chunk of chunks) {
  805. chunkIndexMap.set(
  806. chunk,
  807. index | BigInt((Math.random() * 0x7fffffff) | 0)
  808. );
  809. index = index << ONE;
  810. }
  811. /**
  812. * @param {Iterable<Chunk>} chunks list of chunks
  813. * @returns {bigint | Chunk} key of the chunks
  814. */
  815. const getKey = chunks => {
  816. const iterator = chunks[Symbol.iterator]();
  817. let result = iterator.next();
  818. if (result.done) return ZERO;
  819. const first = result.value;
  820. result = iterator.next();
  821. if (result.done) return first;
  822. let key =
  823. /** @type {bigint} */ (chunkIndexMap.get(first)) |
  824. /** @type {bigint} */ (chunkIndexMap.get(result.value));
  825. while (!(result = iterator.next()).done) {
  826. const raw = chunkIndexMap.get(result.value);
  827. key = key ^ /** @type {bigint} */ (raw);
  828. }
  829. return key;
  830. };
  831. /**
  832. * @param {bigint | Chunk} key key of the chunks
  833. * @returns {string} stringified key
  834. */
  835. const keyToString = key => {
  836. if (typeof key === "bigint") return key.toString(16);
  837. return /** @type {bigint} */ (chunkIndexMap.get(key)).toString(16);
  838. };
  839. const getChunkSetsInGraph = memoize(() => {
  840. /** @type {Map<bigint, Set<Chunk>>} */
  841. const chunkSetsInGraph = new Map();
  842. /** @type {Set<Chunk>} */
  843. const singleChunkSets = new Set();
  844. for (const module of compilation.modules) {
  845. const chunks = chunkGraph.getModuleChunksIterable(module);
  846. const chunksKey = getKey(chunks);
  847. if (typeof chunksKey === "bigint") {
  848. if (!chunkSetsInGraph.has(chunksKey)) {
  849. chunkSetsInGraph.set(chunksKey, new Set(chunks));
  850. }
  851. } else {
  852. singleChunkSets.add(chunksKey);
  853. }
  854. }
  855. return { chunkSetsInGraph, singleChunkSets };
  856. });
  857. /**
  858. * @param {Module} module the module
  859. * @returns {Iterable<Chunk[]>} groups of chunks with equal exports
  860. */
  861. const groupChunksByExports = module => {
  862. const exportsInfo = moduleGraph.getExportsInfo(module);
  863. const groupedByUsedExports = new Map();
  864. for (const chunk of chunkGraph.getModuleChunksIterable(module)) {
  865. const key = exportsInfo.getUsageKey(chunk.runtime);
  866. const list = groupedByUsedExports.get(key);
  867. if (list !== undefined) {
  868. list.push(chunk);
  869. } else {
  870. groupedByUsedExports.set(key, [chunk]);
  871. }
  872. }
  873. return groupedByUsedExports.values();
  874. };
  875. /** @type {Map<Module, Iterable<Chunk[]>>} */
  876. const groupedByExportsMap = new Map();
  877. const getExportsChunkSetsInGraph = memoize(() => {
  878. /** @type {Map<bigint | Chunk, Set<Chunk>>} */
  879. const chunkSetsInGraph = new Map();
  880. /** @type {Set<Chunk>} */
  881. const singleChunkSets = new Set();
  882. for (const module of compilation.modules) {
  883. const groupedChunks = Array.from(groupChunksByExports(module));
  884. groupedByExportsMap.set(module, groupedChunks);
  885. for (const chunks of groupedChunks) {
  886. if (chunks.length === 1) {
  887. singleChunkSets.add(chunks[0]);
  888. } else {
  889. const chunksKey = getKey(chunks);
  890. if (!chunkSetsInGraph.has(chunksKey)) {
  891. chunkSetsInGraph.set(chunksKey, new Set(chunks));
  892. }
  893. }
  894. }
  895. }
  896. return { chunkSetsInGraph, singleChunkSets };
  897. });
  898. // group these set of chunks by count
  899. // to allow to check less sets via isSubset
  900. // (only smaller sets can be subset)
  901. /**
  902. * @param {IterableIterator<Set<Chunk>>} chunkSets set of sets of chunks
  903. * @returns {Map<number, Array<Set<Chunk>>>} map of sets of chunks by count
  904. */
  905. const groupChunkSetsByCount = chunkSets => {
  906. /** @type {Map<number, Array<Set<Chunk>>>} */
  907. const chunkSetsByCount = new Map();
  908. for (const chunksSet of chunkSets) {
  909. const count = chunksSet.size;
  910. let array = chunkSetsByCount.get(count);
  911. if (array === undefined) {
  912. array = [];
  913. chunkSetsByCount.set(count, array);
  914. }
  915. array.push(chunksSet);
  916. }
  917. return chunkSetsByCount;
  918. };
  919. const getChunkSetsByCount = memoize(() =>
  920. groupChunkSetsByCount(
  921. getChunkSetsInGraph().chunkSetsInGraph.values()
  922. )
  923. );
  924. const getExportsChunkSetsByCount = memoize(() =>
  925. groupChunkSetsByCount(
  926. getExportsChunkSetsInGraph().chunkSetsInGraph.values()
  927. )
  928. );
  929. // Create a list of possible combinations
  930. /**
  931. * @param {Map<bigint | Chunk, Set<Chunk>>} chunkSets chunk sets
  932. * @param {Set<Chunk>} singleChunkSets single chunks sets
  933. * @param {Map<number, Set<Chunk>[]>} chunkSetsByCount chunk sets by count
  934. * @returns {(key: bigint | Chunk) => (Set<Chunk> | Chunk)[]} combinations
  935. */
  936. const createGetCombinations = (
  937. chunkSets,
  938. singleChunkSets,
  939. chunkSetsByCount
  940. ) => {
  941. /** @type {Map<bigint | Chunk, (Set<Chunk> | Chunk)[]>} */
  942. const combinationsCache = new Map();
  943. return key => {
  944. const cacheEntry = combinationsCache.get(key);
  945. if (cacheEntry !== undefined) return cacheEntry;
  946. if (key instanceof Chunk) {
  947. const result = [key];
  948. combinationsCache.set(key, result);
  949. return result;
  950. }
  951. const chunksSet =
  952. /** @type {Set<Chunk>} */
  953. (chunkSets.get(key));
  954. /** @type {(Set<Chunk> | Chunk)[]} */
  955. const array = [chunksSet];
  956. for (const [count, setArray] of chunkSetsByCount) {
  957. // "equal" is not needed because they would have been merge in the first step
  958. if (count < chunksSet.size) {
  959. for (const set of setArray) {
  960. if (isSubset(chunksSet, set)) {
  961. array.push(set);
  962. }
  963. }
  964. }
  965. }
  966. for (const chunk of singleChunkSets) {
  967. if (chunksSet.has(chunk)) {
  968. array.push(chunk);
  969. }
  970. }
  971. combinationsCache.set(key, array);
  972. return array;
  973. };
  974. };
  975. const getCombinationsFactory = memoize(() => {
  976. const { chunkSetsInGraph, singleChunkSets } = getChunkSetsInGraph();
  977. return createGetCombinations(
  978. chunkSetsInGraph,
  979. singleChunkSets,
  980. getChunkSetsByCount()
  981. );
  982. });
  983. /**
  984. * @param {bigint | Chunk} key key
  985. * @returns {(Set<Chunk> | Chunk)[]} combinations by key
  986. */
  987. const getCombinations = key => getCombinationsFactory()(key);
  988. const getExportsCombinationsFactory = memoize(() => {
  989. const { chunkSetsInGraph, singleChunkSets } =
  990. getExportsChunkSetsInGraph();
  991. return createGetCombinations(
  992. chunkSetsInGraph,
  993. singleChunkSets,
  994. getExportsChunkSetsByCount()
  995. );
  996. });
  997. /**
  998. * @param {bigint | Chunk} key key
  999. * @returns {(Set<Chunk> | Chunk)[]} exports combinations by key
  1000. */
  1001. const getExportsCombinations = key =>
  1002. getExportsCombinationsFactory()(key);
  1003. /**
  1004. * @typedef {object} SelectedChunksResult
  1005. * @property {Chunk[]} chunks the list of chunks
  1006. * @property {bigint | Chunk} key a key of the list
  1007. */
  1008. /** @type {WeakMap<Set<Chunk> | Chunk, WeakMap<ChunkFilterFunction, SelectedChunksResult>>} */
  1009. const selectedChunksCacheByChunksSet = new WeakMap();
  1010. /**
  1011. * get list and key by applying the filter function to the list
  1012. * It is cached for performance reasons
  1013. * @param {Set<Chunk> | Chunk} chunks list of chunks
  1014. * @param {ChunkFilterFunction} chunkFilter filter function for chunks
  1015. * @returns {SelectedChunksResult} list and key
  1016. */
  1017. const getSelectedChunks = (chunks, chunkFilter) => {
  1018. let entry = selectedChunksCacheByChunksSet.get(chunks);
  1019. if (entry === undefined) {
  1020. entry = new WeakMap();
  1021. selectedChunksCacheByChunksSet.set(chunks, entry);
  1022. }
  1023. let entry2 =
  1024. /** @type {SelectedChunksResult} */
  1025. (entry.get(chunkFilter));
  1026. if (entry2 === undefined) {
  1027. /** @type {Chunk[]} */
  1028. const selectedChunks = [];
  1029. if (chunks instanceof Chunk) {
  1030. if (chunkFilter(chunks)) selectedChunks.push(chunks);
  1031. } else {
  1032. for (const chunk of chunks) {
  1033. if (chunkFilter(chunk)) selectedChunks.push(chunk);
  1034. }
  1035. }
  1036. entry2 = {
  1037. chunks: selectedChunks,
  1038. key: getKey(selectedChunks)
  1039. };
  1040. entry.set(chunkFilter, entry2);
  1041. }
  1042. return entry2;
  1043. };
  1044. /** @type {Map<string, boolean>} */
  1045. const alreadyValidatedParents = new Map();
  1046. /** @type {Set<string>} */
  1047. const alreadyReportedErrors = new Set();
  1048. // Map a list of chunks to a list of modules
  1049. // For the key the chunk "index" is used, the value is a SortableSet of modules
  1050. /** @type {Map<string, ChunksInfoItem>} */
  1051. const chunksInfoMap = new Map();
  1052. /**
  1053. * @param {CacheGroup} cacheGroup the current cache group
  1054. * @param {number} cacheGroupIndex the index of the cache group of ordering
  1055. * @param {Chunk[]} selectedChunks chunks selected for this module
  1056. * @param {bigint | Chunk} selectedChunksKey a key of selectedChunks
  1057. * @param {Module} module the current module
  1058. * @returns {void}
  1059. */
  1060. const addModuleToChunksInfoMap = (
  1061. cacheGroup,
  1062. cacheGroupIndex,
  1063. selectedChunks,
  1064. selectedChunksKey,
  1065. module
  1066. ) => {
  1067. // Break if minimum number of chunks is not reached
  1068. if (selectedChunks.length < cacheGroup.minChunks) return;
  1069. // Determine name for split chunk
  1070. const name =
  1071. /** @type {GetName} */
  1072. (cacheGroup.getName)(module, selectedChunks, cacheGroup.key);
  1073. // Check if the name is ok
  1074. const existingChunk = name && compilation.namedChunks.get(name);
  1075. if (existingChunk) {
  1076. const parentValidationKey = `${name}|${
  1077. typeof selectedChunksKey === "bigint"
  1078. ? selectedChunksKey
  1079. : selectedChunksKey.debugId
  1080. }`;
  1081. const valid = alreadyValidatedParents.get(parentValidationKey);
  1082. if (valid === false) return;
  1083. if (valid === undefined) {
  1084. // Module can only be moved into the existing chunk if the existing chunk
  1085. // is a parent of all selected chunks
  1086. let isInAllParents = true;
  1087. /** @type {Set<ChunkGroup>} */
  1088. const queue = new Set();
  1089. for (const chunk of selectedChunks) {
  1090. for (const group of chunk.groupsIterable) {
  1091. queue.add(group);
  1092. }
  1093. }
  1094. for (const group of queue) {
  1095. if (existingChunk.isInGroup(group)) continue;
  1096. let hasParent = false;
  1097. for (const parent of group.parentsIterable) {
  1098. hasParent = true;
  1099. queue.add(parent);
  1100. }
  1101. if (!hasParent) {
  1102. isInAllParents = false;
  1103. }
  1104. }
  1105. const valid = isInAllParents;
  1106. alreadyValidatedParents.set(parentValidationKey, valid);
  1107. if (!valid) {
  1108. if (!alreadyReportedErrors.has(name)) {
  1109. alreadyReportedErrors.add(name);
  1110. compilation.errors.push(
  1111. new WebpackError(
  1112. "SplitChunksPlugin\n" +
  1113. `Cache group "${cacheGroup.key}" conflicts with existing chunk.\n` +
  1114. `Both have the same name "${name}" and existing chunk is not a parent of the selected modules.\n` +
  1115. "Use a different name for the cache group or make sure that the existing chunk is a parent (e. g. via dependOn).\n" +
  1116. 'HINT: You can omit "name" to automatically create a name.\n' +
  1117. "BREAKING CHANGE: webpack < 5 used to allow to use an entrypoint as splitChunk. " +
  1118. "This is no longer allowed when the entrypoint is not a parent of the selected modules.\n" +
  1119. "Remove this entrypoint and add modules to cache group's 'test' instead. " +
  1120. "If you need modules to be evaluated on startup, add them to the existing entrypoints (make them arrays). " +
  1121. "See migration guide of more info."
  1122. )
  1123. );
  1124. }
  1125. return;
  1126. }
  1127. }
  1128. }
  1129. // Create key for maps
  1130. // When it has a name we use the name as key
  1131. // Otherwise we create the key from chunks and cache group key
  1132. // This automatically merges equal names
  1133. const key =
  1134. cacheGroup.key +
  1135. (name
  1136. ? ` name:${name}`
  1137. : ` chunks:${keyToString(selectedChunksKey)}`);
  1138. // Add module to maps
  1139. let info = chunksInfoMap.get(key);
  1140. if (info === undefined) {
  1141. chunksInfoMap.set(
  1142. key,
  1143. (info = {
  1144. modules: new SortableSet(
  1145. undefined,
  1146. compareModulesByIdentifier
  1147. ),
  1148. cacheGroup,
  1149. cacheGroupIndex,
  1150. name,
  1151. sizes: {},
  1152. chunks: new Set(),
  1153. reusableChunks: new Set(),
  1154. chunksKeys: new Set()
  1155. })
  1156. );
  1157. }
  1158. const oldSize = info.modules.size;
  1159. info.modules.add(module);
  1160. if (info.modules.size !== oldSize) {
  1161. for (const type of module.getSourceTypes()) {
  1162. info.sizes[type] = (info.sizes[type] || 0) + module.size(type);
  1163. }
  1164. }
  1165. const oldChunksKeysSize = info.chunksKeys.size;
  1166. info.chunksKeys.add(selectedChunksKey);
  1167. if (oldChunksKeysSize !== info.chunksKeys.size) {
  1168. for (const chunk of selectedChunks) {
  1169. info.chunks.add(chunk);
  1170. }
  1171. }
  1172. };
  1173. const context = {
  1174. moduleGraph,
  1175. chunkGraph
  1176. };
  1177. logger.timeEnd("prepare");
  1178. logger.time("modules");
  1179. // Walk through all modules
  1180. for (const module of compilation.modules) {
  1181. // Get cache group
  1182. const cacheGroups = this.options.getCacheGroups(module, context);
  1183. if (!Array.isArray(cacheGroups) || cacheGroups.length === 0) {
  1184. continue;
  1185. }
  1186. // Prepare some values (usedExports = false)
  1187. const getCombs = memoize(() => {
  1188. const chunks = chunkGraph.getModuleChunksIterable(module);
  1189. const chunksKey = getKey(chunks);
  1190. return getCombinations(chunksKey);
  1191. });
  1192. // Prepare some values (usedExports = true)
  1193. const getCombsByUsedExports = memoize(() => {
  1194. // fill the groupedByExportsMap
  1195. getExportsChunkSetsInGraph();
  1196. /** @type {Set<Set<Chunk> | Chunk>} */
  1197. const set = new Set();
  1198. const groupedByUsedExports =
  1199. /** @type {Iterable<Chunk[]>} */
  1200. (groupedByExportsMap.get(module));
  1201. for (const chunks of groupedByUsedExports) {
  1202. const chunksKey = getKey(chunks);
  1203. for (const comb of getExportsCombinations(chunksKey))
  1204. set.add(comb);
  1205. }
  1206. return set;
  1207. });
  1208. let cacheGroupIndex = 0;
  1209. for (const cacheGroupSource of cacheGroups) {
  1210. const cacheGroup = this._getCacheGroup(cacheGroupSource);
  1211. const combs = cacheGroup.usedExports
  1212. ? getCombsByUsedExports()
  1213. : getCombs();
  1214. // For all combination of chunk selection
  1215. for (const chunkCombination of combs) {
  1216. // Break if minimum number of chunks is not reached
  1217. const count =
  1218. chunkCombination instanceof Chunk ? 1 : chunkCombination.size;
  1219. if (count < cacheGroup.minChunks) continue;
  1220. // Select chunks by configuration
  1221. const { chunks: selectedChunks, key: selectedChunksKey } =
  1222. getSelectedChunks(
  1223. chunkCombination,
  1224. /** @type {ChunkFilterFunction} */
  1225. (cacheGroup.chunksFilter)
  1226. );
  1227. addModuleToChunksInfoMap(
  1228. cacheGroup,
  1229. cacheGroupIndex,
  1230. selectedChunks,
  1231. selectedChunksKey,
  1232. module
  1233. );
  1234. }
  1235. cacheGroupIndex++;
  1236. }
  1237. }
  1238. logger.timeEnd("modules");
  1239. logger.time("queue");
  1240. /**
  1241. * @param {ChunksInfoItem} info entry
  1242. * @param {string[]} sourceTypes source types to be removed
  1243. */
  1244. const removeModulesWithSourceType = (info, sourceTypes) => {
  1245. for (const module of info.modules) {
  1246. const types = module.getSourceTypes();
  1247. if (sourceTypes.some(type => types.has(type))) {
  1248. info.modules.delete(module);
  1249. for (const type of types) {
  1250. info.sizes[type] -= module.size(type);
  1251. }
  1252. }
  1253. }
  1254. };
  1255. /**
  1256. * @param {ChunksInfoItem} info entry
  1257. * @returns {boolean} true, if entry become empty
  1258. */
  1259. const removeMinSizeViolatingModules = info => {
  1260. if (!info.cacheGroup._validateSize) return false;
  1261. const violatingSizes = getViolatingMinSizes(
  1262. info.sizes,
  1263. info.cacheGroup.minSize
  1264. );
  1265. if (violatingSizes === undefined) return false;
  1266. removeModulesWithSourceType(info, violatingSizes);
  1267. return info.modules.size === 0;
  1268. };
  1269. // Filter items were size < minSize
  1270. for (const [key, info] of chunksInfoMap) {
  1271. if (removeMinSizeViolatingModules(info)) {
  1272. chunksInfoMap.delete(key);
  1273. } else if (
  1274. !checkMinSizeReduction(
  1275. info.sizes,
  1276. info.cacheGroup.minSizeReduction,
  1277. info.chunks.size
  1278. )
  1279. ) {
  1280. chunksInfoMap.delete(key);
  1281. }
  1282. }
  1283. /**
  1284. * @typedef {object} MaxSizeQueueItem
  1285. * @property {SplitChunksSizes} minSize
  1286. * @property {SplitChunksSizes} maxAsyncSize
  1287. * @property {SplitChunksSizes} maxInitialSize
  1288. * @property {string} automaticNameDelimiter
  1289. * @property {string[]} keys
  1290. */
  1291. /** @type {Map<Chunk, MaxSizeQueueItem>} */
  1292. const maxSizeQueueMap = new Map();
  1293. while (chunksInfoMap.size > 0) {
  1294. // Find best matching entry
  1295. let bestEntryKey;
  1296. let bestEntry;
  1297. for (const pair of chunksInfoMap) {
  1298. const key = pair[0];
  1299. const info = pair[1];
  1300. if (
  1301. bestEntry === undefined ||
  1302. compareEntries(bestEntry, info) < 0
  1303. ) {
  1304. bestEntry = info;
  1305. bestEntryKey = key;
  1306. }
  1307. }
  1308. const item = /** @type {ChunksInfoItem} */ (bestEntry);
  1309. chunksInfoMap.delete(/** @type {string} */ (bestEntryKey));
  1310. /** @type {Chunk["name"] | undefined} */
  1311. let chunkName = item.name;
  1312. // Variable for the new chunk (lazy created)
  1313. /** @type {Chunk | undefined} */
  1314. let newChunk;
  1315. // When no chunk name, check if we can reuse a chunk instead of creating a new one
  1316. let isExistingChunk = false;
  1317. let isReusedWithAllModules = false;
  1318. if (chunkName) {
  1319. const chunkByName = compilation.namedChunks.get(chunkName);
  1320. if (chunkByName !== undefined) {
  1321. newChunk = chunkByName;
  1322. const oldSize = item.chunks.size;
  1323. item.chunks.delete(newChunk);
  1324. isExistingChunk = item.chunks.size !== oldSize;
  1325. }
  1326. } else if (item.cacheGroup.reuseExistingChunk) {
  1327. outer: for (const chunk of item.chunks) {
  1328. if (
  1329. chunkGraph.getNumberOfChunkModules(chunk) !==
  1330. item.modules.size
  1331. ) {
  1332. continue;
  1333. }
  1334. if (
  1335. item.chunks.size > 1 &&
  1336. chunkGraph.getNumberOfEntryModules(chunk) > 0
  1337. ) {
  1338. continue;
  1339. }
  1340. for (const module of item.modules) {
  1341. if (!chunkGraph.isModuleInChunk(module, chunk)) {
  1342. continue outer;
  1343. }
  1344. }
  1345. if (!newChunk || !newChunk.name) {
  1346. newChunk = chunk;
  1347. } else if (
  1348. chunk.name &&
  1349. chunk.name.length < newChunk.name.length
  1350. ) {
  1351. newChunk = chunk;
  1352. } else if (
  1353. chunk.name &&
  1354. chunk.name.length === newChunk.name.length &&
  1355. chunk.name < newChunk.name
  1356. ) {
  1357. newChunk = chunk;
  1358. }
  1359. }
  1360. if (newChunk) {
  1361. item.chunks.delete(newChunk);
  1362. chunkName = undefined;
  1363. isExistingChunk = true;
  1364. isReusedWithAllModules = true;
  1365. }
  1366. }
  1367. const enforced =
  1368. item.cacheGroup._conditionalEnforce &&
  1369. checkMinSize(item.sizes, item.cacheGroup.enforceSizeThreshold);
  1370. const usedChunks = new Set(item.chunks);
  1371. // Check if maxRequests condition can be fulfilled
  1372. if (
  1373. !enforced &&
  1374. (Number.isFinite(item.cacheGroup.maxInitialRequests) ||
  1375. Number.isFinite(item.cacheGroup.maxAsyncRequests))
  1376. ) {
  1377. for (const chunk of usedChunks) {
  1378. // respect max requests
  1379. const maxRequests = chunk.isOnlyInitial()
  1380. ? item.cacheGroup.maxInitialRequests
  1381. : chunk.canBeInitial()
  1382. ? Math.min(
  1383. item.cacheGroup.maxInitialRequests,
  1384. item.cacheGroup.maxAsyncRequests
  1385. )
  1386. : item.cacheGroup.maxAsyncRequests;
  1387. if (
  1388. Number.isFinite(maxRequests) &&
  1389. getRequests(chunk) >= maxRequests
  1390. ) {
  1391. usedChunks.delete(chunk);
  1392. }
  1393. }
  1394. }
  1395. outer: for (const chunk of usedChunks) {
  1396. for (const module of item.modules) {
  1397. if (chunkGraph.isModuleInChunk(module, chunk)) continue outer;
  1398. }
  1399. usedChunks.delete(chunk);
  1400. }
  1401. // Were some (invalid) chunks removed from usedChunks?
  1402. // => readd all modules to the queue, as things could have been changed
  1403. if (usedChunks.size < item.chunks.size) {
  1404. if (isExistingChunk)
  1405. usedChunks.add(/** @type {Chunk} */ (newChunk));
  1406. if (usedChunks.size >= item.cacheGroup.minChunks) {
  1407. const chunksArr = Array.from(usedChunks);
  1408. for (const module of item.modules) {
  1409. addModuleToChunksInfoMap(
  1410. item.cacheGroup,
  1411. item.cacheGroupIndex,
  1412. chunksArr,
  1413. getKey(usedChunks),
  1414. module
  1415. );
  1416. }
  1417. }
  1418. continue;
  1419. }
  1420. // Validate minRemainingSize constraint when a single chunk is left over
  1421. if (
  1422. !enforced &&
  1423. item.cacheGroup._validateRemainingSize &&
  1424. usedChunks.size === 1
  1425. ) {
  1426. const [chunk] = usedChunks;
  1427. const chunkSizes = Object.create(null);
  1428. for (const module of chunkGraph.getChunkModulesIterable(chunk)) {
  1429. if (!item.modules.has(module)) {
  1430. for (const type of module.getSourceTypes()) {
  1431. chunkSizes[type] =
  1432. (chunkSizes[type] || 0) + module.size(type);
  1433. }
  1434. }
  1435. }
  1436. const violatingSizes = getViolatingMinSizes(
  1437. chunkSizes,
  1438. item.cacheGroup.minRemainingSize
  1439. );
  1440. if (violatingSizes !== undefined) {
  1441. const oldModulesSize = item.modules.size;
  1442. removeModulesWithSourceType(item, violatingSizes);
  1443. if (
  1444. item.modules.size > 0 &&
  1445. item.modules.size !== oldModulesSize
  1446. ) {
  1447. // queue this item again to be processed again
  1448. // without violating modules
  1449. chunksInfoMap.set(/** @type {string} */ (bestEntryKey), item);
  1450. }
  1451. continue;
  1452. }
  1453. }
  1454. // Create the new chunk if not reusing one
  1455. if (newChunk === undefined) {
  1456. newChunk = compilation.addChunk(chunkName);
  1457. }
  1458. // Walk through all chunks
  1459. for (const chunk of usedChunks) {
  1460. // Add graph connections for splitted chunk
  1461. chunk.split(newChunk);
  1462. }
  1463. // Add a note to the chunk
  1464. newChunk.chunkReason =
  1465. (newChunk.chunkReason ? `${newChunk.chunkReason}, ` : "") +
  1466. (isReusedWithAllModules
  1467. ? "reused as split chunk"
  1468. : "split chunk");
  1469. if (item.cacheGroup.key) {
  1470. newChunk.chunkReason += ` (cache group: ${item.cacheGroup.key})`;
  1471. }
  1472. if (chunkName) {
  1473. newChunk.chunkReason += ` (name: ${chunkName})`;
  1474. }
  1475. if (item.cacheGroup.filename) {
  1476. newChunk.filenameTemplate = item.cacheGroup.filename;
  1477. }
  1478. if (item.cacheGroup.idHint) {
  1479. newChunk.idNameHints.add(item.cacheGroup.idHint);
  1480. }
  1481. if (!isReusedWithAllModules) {
  1482. // Add all modules to the new chunk
  1483. for (const module of item.modules) {
  1484. if (!module.chunkCondition(newChunk, compilation)) continue;
  1485. // Add module to new chunk
  1486. chunkGraph.connectChunkAndModule(newChunk, module);
  1487. // Remove module from used chunks
  1488. for (const chunk of usedChunks) {
  1489. chunkGraph.disconnectChunkAndModule(chunk, module);
  1490. }
  1491. }
  1492. } else {
  1493. // Remove all modules from used chunks
  1494. for (const module of item.modules) {
  1495. for (const chunk of usedChunks) {
  1496. chunkGraph.disconnectChunkAndModule(chunk, module);
  1497. }
  1498. }
  1499. }
  1500. if (
  1501. Object.keys(item.cacheGroup.maxAsyncSize).length > 0 ||
  1502. Object.keys(item.cacheGroup.maxInitialSize).length > 0
  1503. ) {
  1504. const oldMaxSizeSettings = maxSizeQueueMap.get(newChunk);
  1505. maxSizeQueueMap.set(newChunk, {
  1506. minSize: oldMaxSizeSettings
  1507. ? combineSizes(
  1508. oldMaxSizeSettings.minSize,
  1509. item.cacheGroup._minSizeForMaxSize,
  1510. Math.max
  1511. )
  1512. : item.cacheGroup.minSize,
  1513. maxAsyncSize: oldMaxSizeSettings
  1514. ? combineSizes(
  1515. oldMaxSizeSettings.maxAsyncSize,
  1516. item.cacheGroup.maxAsyncSize,
  1517. Math.min
  1518. )
  1519. : item.cacheGroup.maxAsyncSize,
  1520. maxInitialSize: oldMaxSizeSettings
  1521. ? combineSizes(
  1522. oldMaxSizeSettings.maxInitialSize,
  1523. item.cacheGroup.maxInitialSize,
  1524. Math.min
  1525. )
  1526. : item.cacheGroup.maxInitialSize,
  1527. automaticNameDelimiter: item.cacheGroup.automaticNameDelimiter,
  1528. keys: oldMaxSizeSettings
  1529. ? oldMaxSizeSettings.keys.concat(item.cacheGroup.key)
  1530. : [item.cacheGroup.key]
  1531. });
  1532. }
  1533. // remove all modules from other entries and update size
  1534. for (const [key, info] of chunksInfoMap) {
  1535. if (isOverlap(info.chunks, usedChunks)) {
  1536. // update modules and total size
  1537. // may remove it from the map when < minSize
  1538. let updated = false;
  1539. for (const module of item.modules) {
  1540. if (info.modules.has(module)) {
  1541. // remove module
  1542. info.modules.delete(module);
  1543. // update size
  1544. for (const key of module.getSourceTypes()) {
  1545. info.sizes[key] -= module.size(key);
  1546. }
  1547. updated = true;
  1548. }
  1549. }
  1550. if (updated) {
  1551. if (info.modules.size === 0) {
  1552. chunksInfoMap.delete(key);
  1553. continue;
  1554. }
  1555. if (
  1556. removeMinSizeViolatingModules(info) ||
  1557. !checkMinSizeReduction(
  1558. info.sizes,
  1559. info.cacheGroup.minSizeReduction,
  1560. info.chunks.size
  1561. )
  1562. ) {
  1563. chunksInfoMap.delete(key);
  1564. continue;
  1565. }
  1566. }
  1567. }
  1568. }
  1569. }
  1570. logger.timeEnd("queue");
  1571. logger.time("maxSize");
  1572. /** @type {Set<string>} */
  1573. const incorrectMinMaxSizeSet = new Set();
  1574. const { outputOptions } = compilation;
  1575. // Make sure that maxSize is fulfilled
  1576. const { fallbackCacheGroup } = this.options;
  1577. for (const chunk of Array.from(compilation.chunks)) {
  1578. const chunkConfig = maxSizeQueueMap.get(chunk);
  1579. const {
  1580. minSize,
  1581. maxAsyncSize,
  1582. maxInitialSize,
  1583. automaticNameDelimiter
  1584. } = chunkConfig || fallbackCacheGroup;
  1585. if (!chunkConfig && !fallbackCacheGroup.chunksFilter(chunk))
  1586. continue;
  1587. /** @type {SplitChunksSizes} */
  1588. let maxSize;
  1589. if (chunk.isOnlyInitial()) {
  1590. maxSize = maxInitialSize;
  1591. } else if (chunk.canBeInitial()) {
  1592. maxSize = combineSizes(maxAsyncSize, maxInitialSize, Math.min);
  1593. } else {
  1594. maxSize = maxAsyncSize;
  1595. }
  1596. if (Object.keys(maxSize).length === 0) {
  1597. continue;
  1598. }
  1599. for (const key of Object.keys(maxSize)) {
  1600. const maxSizeValue = maxSize[key];
  1601. const minSizeValue = minSize[key];
  1602. if (
  1603. typeof minSizeValue === "number" &&
  1604. minSizeValue > maxSizeValue
  1605. ) {
  1606. const keys = chunkConfig && chunkConfig.keys;
  1607. const warningKey = `${
  1608. keys && keys.join()
  1609. } ${minSizeValue} ${maxSizeValue}`;
  1610. if (!incorrectMinMaxSizeSet.has(warningKey)) {
  1611. incorrectMinMaxSizeSet.add(warningKey);
  1612. compilation.warnings.push(
  1613. new MinMaxSizeWarning(keys, minSizeValue, maxSizeValue)
  1614. );
  1615. }
  1616. }
  1617. }
  1618. const results = deterministicGroupingForModules({
  1619. minSize,
  1620. maxSize: mapObject(maxSize, (value, key) => {
  1621. const minSizeValue = minSize[key];
  1622. return typeof minSizeValue === "number"
  1623. ? Math.max(value, minSizeValue)
  1624. : value;
  1625. }),
  1626. items: chunkGraph.getChunkModulesIterable(chunk),
  1627. getKey(module) {
  1628. const cache = getKeyCache.get(module);
  1629. if (cache !== undefined) return cache;
  1630. const ident = cachedMakePathsRelative(module.identifier());
  1631. const nameForCondition =
  1632. module.nameForCondition && module.nameForCondition();
  1633. const name = nameForCondition
  1634. ? cachedMakePathsRelative(nameForCondition)
  1635. : ident.replace(/^.*!|\?[^?!]*$/g, "");
  1636. const fullKey =
  1637. name +
  1638. automaticNameDelimiter +
  1639. hashFilename(ident, outputOptions);
  1640. const key = requestToId(fullKey);
  1641. getKeyCache.set(module, key);
  1642. return key;
  1643. },
  1644. getSize(module) {
  1645. const size = Object.create(null);
  1646. for (const key of module.getSourceTypes()) {
  1647. size[key] = module.size(key);
  1648. }
  1649. return size;
  1650. }
  1651. });
  1652. if (results.length <= 1) {
  1653. continue;
  1654. }
  1655. for (let i = 0; i < results.length; i++) {
  1656. const group = results[i];
  1657. const key = this.options.hidePathInfo
  1658. ? hashFilename(group.key, outputOptions)
  1659. : group.key;
  1660. let name = chunk.name
  1661. ? chunk.name + automaticNameDelimiter + key
  1662. : null;
  1663. if (name && name.length > 100) {
  1664. name =
  1665. name.slice(0, 100) +
  1666. automaticNameDelimiter +
  1667. hashFilename(name, outputOptions);
  1668. }
  1669. if (i !== results.length - 1) {
  1670. const newPart = compilation.addChunk(name);
  1671. chunk.split(newPart);
  1672. newPart.chunkReason = chunk.chunkReason;
  1673. if (chunk.filenameTemplate) {
  1674. newPart.filenameTemplate = chunk.filenameTemplate;
  1675. }
  1676. // Add all modules to the new chunk
  1677. for (const module of group.items) {
  1678. if (!module.chunkCondition(newPart, compilation)) {
  1679. continue;
  1680. }
  1681. // Add module to new chunk
  1682. chunkGraph.connectChunkAndModule(newPart, module);
  1683. // Remove module from used chunks
  1684. chunkGraph.disconnectChunkAndModule(chunk, module);
  1685. }
  1686. } else {
  1687. // change the chunk to be a part
  1688. chunk.name = name;
  1689. }
  1690. }
  1691. }
  1692. logger.timeEnd("maxSize");
  1693. }
  1694. );
  1695. });
  1696. }
  1697. };