AggressiveSplittingPlugin.js 10 KB

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