SplitChunksPlugin.js 56 KB

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