AggressiveSplittingPlugin.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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 { intersect } = require("../util/SetHelpers");
  8. const {
  9. compareChunks,
  10. compareModulesByIdentifier
  11. } = require("../util/comparators");
  12. const identifierUtils = require("../util/identifier");
  13. /** @typedef {import("../../declarations/plugins/optimize/AggressiveSplittingPlugin").AggressiveSplittingPluginOptions} AggressiveSplittingPluginOptions */
  14. /** @typedef {import("../Chunk")} Chunk */
  15. /** @typedef {import("../Chunk").ChunkId} ChunkId */
  16. /** @typedef {import("../ChunkGraph")} ChunkGraph */
  17. /** @typedef {import("../Compiler")} Compiler */
  18. /** @typedef {import("../Module")} Module */
  19. /**
  20. * Move module between.
  21. * @param {ChunkGraph} chunkGraph the chunk graph
  22. * @param {Chunk} oldChunk the old chunk
  23. * @param {Chunk} newChunk the new chunk
  24. * @returns {(module: Module) => void} function to move module between chunks
  25. */
  26. const moveModuleBetween = (chunkGraph, oldChunk, newChunk) => (module) => {
  27. chunkGraph.disconnectChunkAndModule(oldChunk, module);
  28. chunkGraph.connectChunkAndModule(newChunk, module);
  29. };
  30. /**
  31. * Checks whether this object is not a entry module.
  32. * @param {ChunkGraph} chunkGraph the chunk graph
  33. * @param {Chunk} chunk the chunk
  34. * @returns {(module: Module) => boolean} filter for entry module
  35. */
  36. const isNotAEntryModule = (chunkGraph, chunk) => (module) =>
  37. !chunkGraph.isEntryModuleInChunk(module, chunk);
  38. /** @typedef {{ id?: NonNullable<Chunk["id"]>, hash?: NonNullable<Chunk["hash"]>, modules: string[], size: number }} SplitData */
  39. /** @type {WeakSet<Chunk>} */
  40. const recordedChunks = new WeakSet();
  41. const PLUGIN_NAME = "AggressiveSplittingPlugin";
  42. class AggressiveSplittingPlugin {
  43. /**
  44. * Creates an instance of AggressiveSplittingPlugin.
  45. * @param {AggressiveSplittingPluginOptions=} options options object
  46. */
  47. constructor(options = {}) {
  48. /** @type {AggressiveSplittingPluginOptions} */
  49. this.options = options;
  50. }
  51. /**
  52. * Was chunk recorded.
  53. * @param {Chunk} chunk the chunk to test
  54. * @returns {boolean} true if the chunk was recorded
  55. */
  56. static wasChunkRecorded(chunk) {
  57. return recordedChunks.has(chunk);
  58. }
  59. /**
  60. * Applies the plugin by registering its hooks on the compiler.
  61. * @param {Compiler} compiler the compiler instance
  62. * @returns {void}
  63. */
  64. apply(compiler) {
  65. compiler.hooks.validate.tap(PLUGIN_NAME, () => {
  66. compiler.validate(
  67. () =>
  68. require("../../schemas/plugins/optimize/AggressiveSplittingPlugin.json"),
  69. this.options,
  70. {
  71. name: "Aggressive Splitting Plugin",
  72. baseDataPath: "options"
  73. },
  74. (options) =>
  75. require("../../schemas/plugins/optimize/AggressiveSplittingPlugin.check")(
  76. options
  77. )
  78. );
  79. });
  80. compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => {
  81. let needAdditionalSeal = false;
  82. /** @type {SplitData[]} */
  83. let newSplits;
  84. /** @type {Set<Chunk>} */
  85. let fromAggressiveSplittingSet;
  86. /** @type {Map<Chunk, SplitData>} */
  87. let chunkSplitDataMap;
  88. compilation.hooks.optimize.tap(PLUGIN_NAME, () => {
  89. newSplits = [];
  90. fromAggressiveSplittingSet = new Set();
  91. chunkSplitDataMap = new Map();
  92. });
  93. compilation.hooks.optimizeChunks.tap(
  94. {
  95. name: PLUGIN_NAME,
  96. stage: STAGE_ADVANCED
  97. },
  98. (chunks) => {
  99. const chunkGraph = compilation.chunkGraph;
  100. // Precompute stuff
  101. /** @type {Map<string, Module>} */
  102. const nameToModuleMap = new Map();
  103. /** @type {Map<Module, string>} */
  104. const moduleToNameMap = new Map();
  105. const makePathsRelative =
  106. identifierUtils.makePathsRelative.bindContextCache(
  107. compiler.context,
  108. compiler.root
  109. );
  110. for (const m of compilation.modules) {
  111. const name = makePathsRelative(m.identifier());
  112. nameToModuleMap.set(name, m);
  113. moduleToNameMap.set(m, name);
  114. }
  115. // Check used chunk ids
  116. /** @type {Set<ChunkId>} */
  117. const usedIds = new Set();
  118. for (const chunk of chunks) {
  119. usedIds.add(/** @type {ChunkId} */ (chunk.id));
  120. }
  121. const recordedSplits =
  122. (compilation.records && compilation.records.aggressiveSplits) || [];
  123. const usedSplits = newSplits
  124. ? [...recordedSplits, ...newSplits]
  125. : recordedSplits;
  126. const minSize = this.options.minSize || 30 * 1024;
  127. const maxSize = this.options.maxSize || 50 * 1024;
  128. /**
  129. * Returns true when applied, otherwise false.
  130. * @param {SplitData} splitData split data
  131. * @returns {boolean} true when applied, otherwise false
  132. */
  133. const applySplit = (splitData) => {
  134. // Cannot split if id is already taken
  135. if (splitData.id !== undefined && usedIds.has(splitData.id)) {
  136. return false;
  137. }
  138. // Get module objects from names
  139. const selectedModules = splitData.modules.map(
  140. (name) => /** @type {Module} */ (nameToModuleMap.get(name))
  141. );
  142. // Does the modules exist at all?
  143. if (!selectedModules.every(Boolean)) return false;
  144. // Check if size matches (faster than waiting for hash)
  145. let size = 0;
  146. for (const m of selectedModules) size += m.size();
  147. if (size !== splitData.size) return false;
  148. // get chunks with all modules
  149. const selectedChunks = intersect(
  150. selectedModules.map(
  151. (m) => new Set(chunkGraph.getModuleChunksIterable(m))
  152. )
  153. );
  154. // No relevant chunks found
  155. if (selectedChunks.size === 0) return false;
  156. // The found chunk is already the split or similar
  157. if (
  158. selectedChunks.size === 1 &&
  159. chunkGraph.getNumberOfChunkModules([...selectedChunks][0]) ===
  160. selectedModules.length
  161. ) {
  162. const chunk = [...selectedChunks][0];
  163. if (fromAggressiveSplittingSet.has(chunk)) return false;
  164. fromAggressiveSplittingSet.add(chunk);
  165. chunkSplitDataMap.set(chunk, splitData);
  166. return true;
  167. }
  168. // split the chunk into two parts
  169. const newChunk = compilation.addChunk();
  170. newChunk.chunkReason = "aggressive splitted";
  171. for (const chunk of selectedChunks) {
  172. for (const module of selectedModules) {
  173. moveModuleBetween(chunkGraph, chunk, newChunk)(module);
  174. }
  175. chunk.split(newChunk);
  176. chunk.name = null;
  177. }
  178. fromAggressiveSplittingSet.add(newChunk);
  179. chunkSplitDataMap.set(newChunk, splitData);
  180. if (splitData.id !== null && splitData.id !== undefined) {
  181. newChunk.id = splitData.id;
  182. newChunk.ids = [splitData.id];
  183. }
  184. return true;
  185. };
  186. // try to restore to recorded splitting
  187. let changed = false;
  188. for (let j = 0; j < usedSplits.length; j++) {
  189. const splitData = usedSplits[j];
  190. if (applySplit(splitData)) changed = true;
  191. }
  192. // for any chunk which isn't splitted yet, split it and create a new entry
  193. // start with the biggest chunk
  194. const cmpFn = compareChunks(chunkGraph);
  195. const sortedChunks = [...chunks].sort((a, b) => {
  196. const diff1 =
  197. chunkGraph.getChunkModulesSize(b) -
  198. chunkGraph.getChunkModulesSize(a);
  199. if (diff1) return diff1;
  200. const diff2 =
  201. chunkGraph.getNumberOfChunkModules(a) -
  202. chunkGraph.getNumberOfChunkModules(b);
  203. if (diff2) return diff2;
  204. return cmpFn(a, b);
  205. });
  206. for (const chunk of sortedChunks) {
  207. if (fromAggressiveSplittingSet.has(chunk)) continue;
  208. const size = chunkGraph.getChunkModulesSize(chunk);
  209. if (
  210. size > maxSize &&
  211. chunkGraph.getNumberOfChunkModules(chunk) > 1
  212. ) {
  213. const modules = chunkGraph
  214. .getOrderedChunkModules(chunk, compareModulesByIdentifier)
  215. .filter(isNotAEntryModule(chunkGraph, chunk));
  216. /** @type {Module[]} */
  217. const selectedModules = [];
  218. let selectedModulesSize = 0;
  219. for (let k = 0; k < modules.length; k++) {
  220. const module = modules[k];
  221. const newSize = selectedModulesSize + module.size();
  222. if (newSize > maxSize && selectedModulesSize >= minSize) {
  223. break;
  224. }
  225. selectedModulesSize = newSize;
  226. selectedModules.push(module);
  227. }
  228. if (selectedModules.length === 0) continue;
  229. /** @type {SplitData} */
  230. const splitData = {
  231. modules: selectedModules
  232. .map((m) => /** @type {string} */ (moduleToNameMap.get(m)))
  233. .sort(),
  234. size: selectedModulesSize
  235. };
  236. if (applySplit(splitData)) {
  237. newSplits = [...(newSplits || []), splitData];
  238. changed = true;
  239. }
  240. }
  241. }
  242. if (changed) return true;
  243. }
  244. );
  245. compilation.hooks.recordHash.tap(PLUGIN_NAME, (records) => {
  246. // 4. save made splittings to records
  247. /** @type {Set<SplitData>} */
  248. const allSplits = new Set();
  249. /** @type {Set<SplitData>} */
  250. const invalidSplits = new Set();
  251. // Check if some splittings are invalid
  252. // We remove invalid splittings and try again
  253. for (const chunk of compilation.chunks) {
  254. const splitData = chunkSplitDataMap.get(chunk);
  255. if (
  256. splitData !== undefined &&
  257. splitData.hash &&
  258. chunk.hash !== splitData.hash
  259. ) {
  260. // Split was successful, but hash doesn't equal
  261. // We can throw away the split since it's useless now
  262. invalidSplits.add(splitData);
  263. }
  264. }
  265. if (invalidSplits.size > 0) {
  266. records.aggressiveSplits =
  267. /** @type {SplitData[]} */
  268. (records.aggressiveSplits).filter(
  269. (splitData) => !invalidSplits.has(splitData)
  270. );
  271. needAdditionalSeal = true;
  272. } else {
  273. // set hash and id values on all (new) splittings
  274. for (const chunk of compilation.chunks) {
  275. const splitData = chunkSplitDataMap.get(chunk);
  276. if (splitData !== undefined) {
  277. splitData.hash =
  278. /** @type {NonNullable<Chunk["hash"]>} */
  279. (chunk.hash);
  280. splitData.id =
  281. /** @type {NonNullable<Chunk["id"]>} */
  282. (chunk.id);
  283. allSplits.add(splitData);
  284. // set flag for stats
  285. recordedChunks.add(chunk);
  286. }
  287. }
  288. // Also add all unused historical splits (after the used ones)
  289. // They can still be used in some future compilation
  290. const recordedSplits =
  291. compilation.records && compilation.records.aggressiveSplits;
  292. if (recordedSplits) {
  293. for (const splitData of recordedSplits) {
  294. if (!invalidSplits.has(splitData)) allSplits.add(splitData);
  295. }
  296. }
  297. // record all splits
  298. records.aggressiveSplits = [...allSplits];
  299. needAdditionalSeal = false;
  300. }
  301. });
  302. compilation.hooks.needAdditionalSeal.tap(PLUGIN_NAME, () => {
  303. if (needAdditionalSeal) {
  304. needAdditionalSeal = false;
  305. return true;
  306. }
  307. });
  308. });
  309. }
  310. }
  311. module.exports = AggressiveSplittingPlugin;