SplitChunksPlugin.js 53 KB

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