LimitChunkCountPlugin.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. class LimitChunkCountPlugin {
  7. constructor(options) {
  8. if(options !== undefined && typeof options !== "object" || Array.isArray(options)) {
  9. throw new Error("Argument should be an options object.\nFor more info on options, see https://webpack.js.org/plugins/");
  10. }
  11. this.options = options || {};
  12. }
  13. apply(compiler) {
  14. const options = this.options;
  15. compiler.plugin("compilation", (compilation) => {
  16. compilation.plugin("optimize-chunks-advanced", (chunks) => {
  17. const maxChunks = options.maxChunks;
  18. if(!maxChunks) return;
  19. if(maxChunks < 1) return;
  20. if(chunks.length <= maxChunks) return;
  21. if(chunks.length > maxChunks) {
  22. const sortedExtendedPairCombinations = chunks.reduce((combinations, a, idx) => {
  23. // create combination pairs
  24. for(let i = 0; i < idx; i++) {
  25. const b = chunks[i];
  26. combinations.push([b, a]);
  27. }
  28. return combinations;
  29. }, []).map((pair) => {
  30. // extend combination pairs with size and integrated size
  31. const a = pair[0].size(options);
  32. const b = pair[1].size(options);
  33. const ab = pair[0].integratedSize(pair[1], options);
  34. return [a + b - ab, ab, pair[0], pair[1], a, b];
  35. }).filter((extendedPair) => {
  36. // filter pairs that do not have an integratedSize
  37. // meaning they can NOT be integrated!
  38. return extendedPair[1] !== false;
  39. }).sort((a, b) => { // sadly javascript does an inplace sort here
  40. // sort them by size
  41. const diff = b[0] - a[0];
  42. if(diff !== 0) return diff;
  43. return a[1] - b[1];
  44. });
  45. const pair = sortedExtendedPairCombinations[0];
  46. if(pair && pair[2].integrate(pair[3], "limit")) {
  47. chunks.splice(chunks.indexOf(pair[3]), 1);
  48. return true;
  49. }
  50. }
  51. });
  52. });
  53. }
  54. }
  55. module.exports = LimitChunkCountPlugin;