LimitChunkCountPlugin.js 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const { STAGE_ADVANCED } = require("../OptimizationStages");
  7. const LazyBucketSortedSet = require("../util/LazyBucketSortedSet");
  8. const { compareChunks } = require("../util/comparators");
  9. const createSchemaValidation = require("../util/create-schema-validation");
  10. /** @typedef {import("../../declarations/plugins/optimize/LimitChunkCountPlugin").LimitChunkCountPluginOptions} LimitChunkCountPluginOptions */
  11. /** @typedef {import("../Chunk")} Chunk */
  12. /** @typedef {import("../Compiler")} Compiler */
  13. const validate = createSchemaValidation(
  14. require("../../schemas/plugins/optimize/LimitChunkCountPlugin.check.js"),
  15. () => require("../../schemas/plugins/optimize/LimitChunkCountPlugin.json"),
  16. {
  17. name: "Limit Chunk Count Plugin",
  18. baseDataPath: "options"
  19. }
  20. );
  21. /**
  22. * @typedef {object} ChunkCombination
  23. * @property {boolean} deleted this is set to true when combination was removed
  24. * @property {number} sizeDiff
  25. * @property {number} integratedSize
  26. * @property {Chunk} a
  27. * @property {Chunk} b
  28. * @property {number} aIdx
  29. * @property {number} bIdx
  30. * @property {number} aSize
  31. * @property {number} bSize
  32. */
  33. /**
  34. * @template K, V
  35. * @param {Map<K, Set<V>>} map map
  36. * @param {K} key key
  37. * @param {V} value value
  38. */
  39. const addToSetMap = (map, key, value) => {
  40. const set = map.get(key);
  41. if (set === undefined) {
  42. map.set(key, new Set([value]));
  43. } else {
  44. set.add(value);
  45. }
  46. };
  47. const PLUGIN_NAME = "LimitChunkCountPlugin";
  48. class LimitChunkCountPlugin {
  49. /**
  50. * @param {LimitChunkCountPluginOptions=} options options object
  51. */
  52. constructor(options) {
  53. validate(options);
  54. this.options = /** @type {LimitChunkCountPluginOptions} */ (options);
  55. }
  56. /**
  57. * @param {Compiler} compiler the webpack compiler
  58. * @returns {void}
  59. */
  60. apply(compiler) {
  61. const options = this.options;
  62. compiler.hooks.compilation.tap(PLUGIN_NAME, compilation => {
  63. compilation.hooks.optimizeChunks.tap(
  64. {
  65. name: PLUGIN_NAME,
  66. stage: STAGE_ADVANCED
  67. },
  68. chunks => {
  69. const chunkGraph = compilation.chunkGraph;
  70. const maxChunks = options.maxChunks;
  71. if (!maxChunks) return;
  72. if (maxChunks < 1) return;
  73. if (compilation.chunks.size <= maxChunks) return;
  74. let remainingChunksToMerge = compilation.chunks.size - maxChunks;
  75. // order chunks in a deterministic way
  76. const compareChunksWithGraph = compareChunks(chunkGraph);
  77. const orderedChunks = Array.from(chunks).sort(compareChunksWithGraph);
  78. // create a lazy sorted data structure to keep all combinations
  79. // this is large. Size = chunks * (chunks - 1) / 2
  80. // It uses a multi layer bucket sort plus normal sort in the last layer
  81. // It's also lazy so only accessed buckets are sorted
  82. /** @type {LazyBucketSortedSet<ChunkCombination, number>} */
  83. const combinations = new LazyBucketSortedSet(
  84. // Layer 1: ordered by largest size benefit
  85. c => c.sizeDiff,
  86. (a, b) => b - a,
  87. // Layer 2: ordered by smallest combined size
  88. /**
  89. * @param {ChunkCombination} c combination
  90. * @returns {number} integrated size
  91. */
  92. c => c.integratedSize,
  93. /**
  94. * @param {number} a a
  95. * @param {number} b b
  96. * @returns {number} result
  97. */
  98. (a, b) => a - b,
  99. // Layer 3: ordered by position difference in orderedChunk (-> to be deterministic)
  100. /**
  101. * @param {ChunkCombination} c combination
  102. * @returns {number} position difference
  103. */
  104. c => c.bIdx - c.aIdx,
  105. /**
  106. * @param {number} a a
  107. * @param {number} b b
  108. * @returns {number} result
  109. */
  110. (a, b) => a - b,
  111. // Layer 4: ordered by position in orderedChunk (-> to be deterministic)
  112. /**
  113. * @param {ChunkCombination} a a
  114. * @param {ChunkCombination} b b
  115. * @returns {number} result
  116. */
  117. (a, b) => a.bIdx - b.bIdx
  118. );
  119. // we keep a mapping from chunk to all combinations
  120. // but this mapping is not kept up-to-date with deletions
  121. // so `deleted` flag need to be considered when iterating this
  122. /** @type {Map<Chunk, Set<ChunkCombination>>} */
  123. const combinationsByChunk = new Map();
  124. for (const [bIdx, b] of orderedChunks.entries()) {
  125. // create combination pairs with size and integrated size
  126. for (let aIdx = 0; aIdx < bIdx; aIdx++) {
  127. const a = orderedChunks[aIdx];
  128. // filter pairs that can not be integrated!
  129. if (!chunkGraph.canChunksBeIntegrated(a, b)) continue;
  130. const integratedSize = chunkGraph.getIntegratedChunksSize(
  131. a,
  132. b,
  133. options
  134. );
  135. const aSize = chunkGraph.getChunkSize(a, options);
  136. const bSize = chunkGraph.getChunkSize(b, options);
  137. /** @type {ChunkCombination} */
  138. const c = {
  139. deleted: false,
  140. sizeDiff: aSize + bSize - integratedSize,
  141. integratedSize,
  142. a,
  143. b,
  144. aIdx,
  145. bIdx,
  146. aSize,
  147. bSize
  148. };
  149. combinations.add(c);
  150. addToSetMap(combinationsByChunk, a, c);
  151. addToSetMap(combinationsByChunk, b, c);
  152. }
  153. }
  154. // list of modified chunks during this run
  155. // combinations affected by this change are skipped to allow
  156. // further optimizations
  157. /** @type {Set<Chunk>} */
  158. const modifiedChunks = new Set();
  159. let changed = false;
  160. loop: while (true) {
  161. const combination = combinations.popFirst();
  162. if (combination === undefined) break;
  163. combination.deleted = true;
  164. const { a, b, integratedSize } = combination;
  165. // skip over pair when
  166. // one of the already merged chunks is a parent of one of the chunks
  167. if (modifiedChunks.size > 0) {
  168. const queue = new Set(a.groupsIterable);
  169. for (const group of b.groupsIterable) {
  170. queue.add(group);
  171. }
  172. for (const group of queue) {
  173. for (const mChunk of modifiedChunks) {
  174. if (mChunk !== a && mChunk !== b && mChunk.isInGroup(group)) {
  175. // This is a potential pair which needs recalculation
  176. // We can't do that now, but it merge before following pairs
  177. // so we leave space for it, and consider chunks as modified
  178. // just for the worse case
  179. remainingChunksToMerge--;
  180. if (remainingChunksToMerge <= 0) break loop;
  181. modifiedChunks.add(a);
  182. modifiedChunks.add(b);
  183. continue loop;
  184. }
  185. }
  186. for (const parent of group.parentsIterable) {
  187. queue.add(parent);
  188. }
  189. }
  190. }
  191. // merge the chunks
  192. if (chunkGraph.canChunksBeIntegrated(a, b)) {
  193. chunkGraph.integrateChunks(a, b);
  194. compilation.chunks.delete(b);
  195. // flag chunk a as modified as further optimization are possible for all children here
  196. modifiedChunks.add(a);
  197. changed = true;
  198. remainingChunksToMerge--;
  199. if (remainingChunksToMerge <= 0) break;
  200. // Update all affected combinations
  201. // delete all combination with the removed chunk
  202. // we will use combinations with the kept chunk instead
  203. for (const combination of /** @type {Set<ChunkCombination>} */ (
  204. combinationsByChunk.get(a)
  205. )) {
  206. if (combination.deleted) continue;
  207. combination.deleted = true;
  208. combinations.delete(combination);
  209. }
  210. // Update combinations with the kept chunk with new sizes
  211. for (const combination of /** @type {Set<ChunkCombination>} */ (
  212. combinationsByChunk.get(b)
  213. )) {
  214. if (combination.deleted) continue;
  215. if (combination.a === b) {
  216. if (!chunkGraph.canChunksBeIntegrated(a, combination.b)) {
  217. combination.deleted = true;
  218. combinations.delete(combination);
  219. continue;
  220. }
  221. // Update size
  222. const newIntegratedSize = chunkGraph.getIntegratedChunksSize(
  223. a,
  224. combination.b,
  225. options
  226. );
  227. const finishUpdate = combinations.startUpdate(combination);
  228. combination.a = a;
  229. combination.integratedSize = newIntegratedSize;
  230. combination.aSize = integratedSize;
  231. combination.sizeDiff =
  232. combination.bSize + integratedSize - newIntegratedSize;
  233. finishUpdate();
  234. } else if (combination.b === b) {
  235. if (!chunkGraph.canChunksBeIntegrated(combination.a, a)) {
  236. combination.deleted = true;
  237. combinations.delete(combination);
  238. continue;
  239. }
  240. // Update size
  241. const newIntegratedSize = chunkGraph.getIntegratedChunksSize(
  242. combination.a,
  243. a,
  244. options
  245. );
  246. const finishUpdate = combinations.startUpdate(combination);
  247. combination.b = a;
  248. combination.integratedSize = newIntegratedSize;
  249. combination.bSize = integratedSize;
  250. combination.sizeDiff =
  251. integratedSize + combination.aSize - newIntegratedSize;
  252. finishUpdate();
  253. }
  254. }
  255. combinationsByChunk.set(
  256. a,
  257. /** @type {Set<ChunkCombination>} */ (
  258. combinationsByChunk.get(b)
  259. )
  260. );
  261. combinationsByChunk.delete(b);
  262. }
  263. }
  264. if (changed) return true;
  265. }
  266. );
  267. });
  268. }
  269. }
  270. module.exports = LimitChunkCountPlugin;