AggressiveSplittingPlugin.js 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const identifierUtils = require("../util/identifier");
  7. const { intersect } = require("../util/SetHelpers");
  8. const validateOptions = require("schema-utils");
  9. const schema = require("../../schemas/plugins/optimize/AggressiveSplittingPlugin.json");
  10. /** @typedef {import("../../declarations/plugins/optimize/AggressiveSplittingPlugin").AggressiveSplittingPluginOptions} AggressiveSplittingPluginOptions */
  11. const moveModuleBetween = (oldChunk, newChunk) => {
  12. return module => {
  13. oldChunk.moveModule(module, newChunk);
  14. };
  15. };
  16. const isNotAEntryModule = entryModule => {
  17. return module => {
  18. return entryModule !== module;
  19. };
  20. };
  21. class AggressiveSplittingPlugin {
  22. /**
  23. * @param {AggressiveSplittingPluginOptions=} options options object
  24. */
  25. constructor(options) {
  26. if (!options) options = {};
  27. validateOptions(schema, options, "Aggressive Splitting Plugin");
  28. this.options = options;
  29. if (typeof this.options.minSize !== "number") {
  30. this.options.minSize = 30 * 1024;
  31. }
  32. if (typeof this.options.maxSize !== "number") {
  33. this.options.maxSize = 50 * 1024;
  34. }
  35. if (typeof this.options.chunkOverhead !== "number") {
  36. this.options.chunkOverhead = 0;
  37. }
  38. if (typeof this.options.entryChunkMultiplicator !== "number") {
  39. this.options.entryChunkMultiplicator = 1;
  40. }
  41. }
  42. apply(compiler) {
  43. compiler.hooks.thisCompilation.tap(
  44. "AggressiveSplittingPlugin",
  45. compilation => {
  46. let needAdditionalSeal = false;
  47. let newSplits;
  48. let fromAggressiveSplittingSet;
  49. let chunkSplitDataMap;
  50. compilation.hooks.optimize.tap("AggressiveSplittingPlugin", () => {
  51. newSplits = [];
  52. fromAggressiveSplittingSet = new Set();
  53. chunkSplitDataMap = new Map();
  54. });
  55. compilation.hooks.optimizeChunksAdvanced.tap(
  56. "AggressiveSplittingPlugin",
  57. chunks => {
  58. // Precompute stuff
  59. const nameToModuleMap = new Map();
  60. const moduleToNameMap = new Map();
  61. for (const m of compilation.modules) {
  62. const name = identifierUtils.makePathsRelative(
  63. compiler.context,
  64. m.identifier(),
  65. compilation.cache
  66. );
  67. nameToModuleMap.set(name, m);
  68. moduleToNameMap.set(m, name);
  69. }
  70. // Check used chunk ids
  71. const usedIds = new Set();
  72. for (const chunk of chunks) {
  73. usedIds.add(chunk.id);
  74. }
  75. const recordedSplits =
  76. (compilation.records && compilation.records.aggressiveSplits) ||
  77. [];
  78. const usedSplits = newSplits
  79. ? recordedSplits.concat(newSplits)
  80. : recordedSplits;
  81. const minSize = this.options.minSize;
  82. const maxSize = this.options.maxSize;
  83. const applySplit = splitData => {
  84. // Cannot split if id is already taken
  85. if (splitData.id !== undefined && usedIds.has(splitData.id)) {
  86. return false;
  87. }
  88. // Get module objects from names
  89. const selectedModules = splitData.modules.map(name =>
  90. nameToModuleMap.get(name)
  91. );
  92. // Does the modules exist at all?
  93. if (!selectedModules.every(Boolean)) return false;
  94. // Check if size matches (faster than waiting for hash)
  95. const size = selectedModules.reduce(
  96. (sum, m) => sum + m.size(),
  97. 0
  98. );
  99. if (size !== splitData.size) return false;
  100. // get chunks with all modules
  101. const selectedChunks = intersect(
  102. selectedModules.map(m => new Set(m.chunksIterable))
  103. );
  104. // No relevant chunks found
  105. if (selectedChunks.size === 0) return false;
  106. // The found chunk is already the split or similar
  107. if (
  108. selectedChunks.size === 1 &&
  109. Array.from(selectedChunks)[0].getNumberOfModules() ===
  110. selectedModules.length
  111. ) {
  112. const chunk = Array.from(selectedChunks)[0];
  113. if (fromAggressiveSplittingSet.has(chunk)) return false;
  114. fromAggressiveSplittingSet.add(chunk);
  115. chunkSplitDataMap.set(chunk, splitData);
  116. return true;
  117. }
  118. // split the chunk into two parts
  119. const newChunk = compilation.addChunk();
  120. newChunk.chunkReason = "aggressive splitted";
  121. for (const chunk of selectedChunks) {
  122. selectedModules.forEach(moveModuleBetween(chunk, newChunk));
  123. chunk.split(newChunk);
  124. chunk.name = null;
  125. }
  126. fromAggressiveSplittingSet.add(newChunk);
  127. chunkSplitDataMap.set(newChunk, splitData);
  128. if (splitData.id !== null && splitData.id !== undefined) {
  129. newChunk.id = splitData.id;
  130. }
  131. return true;
  132. };
  133. // try to restore to recorded splitting
  134. let changed = false;
  135. for (let j = 0; j < usedSplits.length; j++) {
  136. const splitData = usedSplits[j];
  137. if (applySplit(splitData)) changed = true;
  138. }
  139. // for any chunk which isn't splitted yet, split it and create a new entry
  140. // start with the biggest chunk
  141. const sortedChunks = chunks.slice().sort((a, b) => {
  142. const diff1 = b.modulesSize() - a.modulesSize();
  143. if (diff1) return diff1;
  144. const diff2 = a.getNumberOfModules() - b.getNumberOfModules();
  145. if (diff2) return diff2;
  146. const modulesA = Array.from(a.modulesIterable);
  147. const modulesB = Array.from(b.modulesIterable);
  148. modulesA.sort();
  149. modulesB.sort();
  150. const aI = modulesA[Symbol.iterator]();
  151. const bI = modulesB[Symbol.iterator]();
  152. // eslint-disable-next-line no-constant-condition
  153. while (true) {
  154. const aItem = aI.next();
  155. const bItem = bI.next();
  156. if (aItem.done) return 0;
  157. const aModuleIdentifier = aItem.value.identifier();
  158. const bModuleIdentifier = bItem.value.identifier();
  159. if (aModuleIdentifier > bModuleIdentifier) return -1;
  160. if (aModuleIdentifier < bModuleIdentifier) return 1;
  161. }
  162. });
  163. for (const chunk of sortedChunks) {
  164. if (fromAggressiveSplittingSet.has(chunk)) continue;
  165. const size = chunk.modulesSize();
  166. if (size > maxSize && chunk.getNumberOfModules() > 1) {
  167. const modules = chunk
  168. .getModules()
  169. .filter(isNotAEntryModule(chunk.entryModule))
  170. .sort((a, b) => {
  171. a = a.identifier();
  172. b = b.identifier();
  173. if (a > b) return 1;
  174. if (a < b) return -1;
  175. return 0;
  176. });
  177. const selectedModules = [];
  178. let selectedModulesSize = 0;
  179. for (let k = 0; k < modules.length; k++) {
  180. const module = modules[k];
  181. const newSize = selectedModulesSize + module.size();
  182. if (newSize > maxSize && selectedModulesSize >= minSize) {
  183. break;
  184. }
  185. selectedModulesSize = newSize;
  186. selectedModules.push(module);
  187. }
  188. if (selectedModules.length === 0) continue;
  189. const splitData = {
  190. modules: selectedModules
  191. .map(m => moduleToNameMap.get(m))
  192. .sort(),
  193. size: selectedModulesSize
  194. };
  195. if (applySplit(splitData)) {
  196. newSplits = (newSplits || []).concat(splitData);
  197. changed = true;
  198. }
  199. }
  200. }
  201. if (changed) return true;
  202. }
  203. );
  204. compilation.hooks.recordHash.tap(
  205. "AggressiveSplittingPlugin",
  206. records => {
  207. // 4. save made splittings to records
  208. const allSplits = new Set();
  209. const invalidSplits = new Set();
  210. // Check if some splittings are invalid
  211. // We remove invalid splittings and try again
  212. for (const chunk of compilation.chunks) {
  213. const splitData = chunkSplitDataMap.get(chunk);
  214. if (splitData !== undefined) {
  215. if (splitData.hash && chunk.hash !== splitData.hash) {
  216. // Split was successful, but hash doesn't equal
  217. // We can throw away the split since it's useless now
  218. invalidSplits.add(splitData);
  219. }
  220. }
  221. }
  222. if (invalidSplits.size > 0) {
  223. records.aggressiveSplits = records.aggressiveSplits.filter(
  224. splitData => !invalidSplits.has(splitData)
  225. );
  226. needAdditionalSeal = true;
  227. } else {
  228. // set hash and id values on all (new) splittings
  229. for (const chunk of compilation.chunks) {
  230. const splitData = chunkSplitDataMap.get(chunk);
  231. if (splitData !== undefined) {
  232. splitData.hash = chunk.hash;
  233. splitData.id = chunk.id;
  234. allSplits.add(splitData);
  235. // set flag for stats
  236. chunk.recorded = true;
  237. }
  238. }
  239. // Also add all unused historial splits (after the used ones)
  240. // They can still be used in some future compilation
  241. const recordedSplits =
  242. compilation.records && compilation.records.aggressiveSplits;
  243. if (recordedSplits) {
  244. for (const splitData of recordedSplits) {
  245. if (!invalidSplits.has(splitData)) allSplits.add(splitData);
  246. }
  247. }
  248. // record all splits
  249. records.aggressiveSplits = Array.from(allSplits);
  250. needAdditionalSeal = false;
  251. }
  252. }
  253. );
  254. compilation.hooks.needAdditionalSeal.tap(
  255. "AggressiveSplittingPlugin",
  256. () => {
  257. if (needAdditionalSeal) {
  258. needAdditionalSeal = false;
  259. return true;
  260. }
  261. }
  262. );
  263. }
  264. );
  265. }
  266. }
  267. module.exports = AggressiveSplittingPlugin;