SplitChunksPlugin.js 55 KB

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