MinChunkSizePlugin.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. class MinChunkSizePlugin {
  7. constructor(options) {
  8. if(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. const minChunkSize = options.minChunkSize;
  16. compiler.plugin("compilation", (compilation) => {
  17. compilation.plugin("optimize-chunks-advanced", (chunks) => {
  18. const equalOptions = {
  19. chunkOverhead: 1,
  20. entryChunkMultiplicator: 1
  21. };
  22. const sortedSizeFilteredExtendedPairCombinations = 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. }, []).filter((pair) => {
  30. // check if one of the chunks sizes is smaller than the minChunkSize
  31. const p0SmallerThanMinChunkSize = pair[0].size(equalOptions) < minChunkSize;
  32. const p1SmallerThanMinChunkSize = pair[1].size(equalOptions) < minChunkSize;
  33. return p0SmallerThanMinChunkSize || p1SmallerThanMinChunkSize;
  34. }).map((pair) => {
  35. // extend combination pairs with size and integrated size
  36. const a = pair[0].size(options);
  37. const b = pair[1].size(options);
  38. const ab = pair[0].integratedSize(pair[1], options);
  39. return [a + b - ab, ab, pair[0], pair[1]];
  40. }).filter((pair) => {
  41. // filter pairs that do not have an integratedSize
  42. // meaning they can NOT be integrated!
  43. return pair[1] !== false;
  44. }).sort((a, b) => { // sadly javascript does an inplace sort here
  45. // sort by size
  46. const diff = b[0] - a[0];
  47. if(diff !== 0) return diff;
  48. return a[1] - b[1];
  49. });
  50. if(sortedSizeFilteredExtendedPairCombinations.length === 0) return;
  51. const pair = sortedSizeFilteredExtendedPairCombinations[0];
  52. pair[2].integrate(pair[3], "min-size");
  53. chunks.splice(chunks.indexOf(pair[3]), 1);
  54. return true;
  55. });
  56. });
  57. }
  58. }
  59. module.exports = MinChunkSizePlugin;