webpack/lib/optimize/LimitChunkCountPlugin.js

86 lines
2.5 KiB
JavaScript
Raw Normal View History

2013-01-31 01:49:25 +08:00
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
2018-07-30 23:08:51 +08:00
"use strict";
2013-01-31 01:49:25 +08:00
const validateOptions = require("schema-utils");
const schema = require("../../schemas/plugins/optimize/LimitChunkCountPlugin.json");
const { STAGE_ADVANCED } = require("../OptimizationStages");
2017-10-28 05:23:38 +08:00
/** @typedef {import("../Chunk")} Chunk */
/** @typedef {import("../Compiler")} Compiler */
class LimitChunkCountPlugin {
constructor(options) {
validateOptions(schema, options || {}, "Limit Chunk Count Plugin");
this.options = options || {};
}
/**
* @param {Compiler} compiler webpack compiler
* @returns {void}
*/
apply(compiler) {
const options = this.options;
2018-02-25 09:00:20 +08:00
compiler.hooks.compilation.tap("LimitChunkCountPlugin", compilation => {
compilation.hooks.optimizeChunks.tap(
/** @type {TODO} */ ({
name: "LimitChunkCountPlugin",
stage: STAGE_ADVANCED
}),
2018-02-25 09:00:20 +08:00
chunks => {
const chunkGraph = compilation.chunkGraph;
2018-02-25 09:00:20 +08:00
const maxChunks = options.maxChunks;
if (!maxChunks) return;
if (maxChunks < 1) return;
if (chunks.length <= maxChunks) return;
2013-01-31 01:49:25 +08:00
2018-02-25 09:00:20 +08:00
const sortedExtendedPairCombinations = chunks
.reduce((/** @type {[Chunk, Chunk][]} */ combinations, a, idx) => {
2018-02-25 09:00:20 +08:00
// create combination pairs
for (let i = 0; i < idx; i++) {
const b = chunks[i];
// filter pairs that can NOT be integrated!
if (chunkGraph.canChunksBeIntegrated(b, a)) {
combinations.push([b, a]);
}
2018-02-25 09:00:20 +08:00
}
return combinations;
}, [])
.map(pair => {
// extend combination pairs with size and integrated size
const a = chunkGraph.getChunkSize(pair[0], options);
const b = chunkGraph.getChunkSize(pair[1], options);
const ab = chunkGraph.getIntegratedChunksSize(
pair[0],
pair[1],
options
);
/** @type {[number, number, Chunk, Chunk, number, number]} */
const extendedPair = [a + b - ab, ab, pair[0], pair[1], a, b];
return extendedPair;
2018-02-25 09:00:20 +08:00
})
.sort((a, b) => {
// sadly javascript does an inplace sort here
// sort them by size
const diff = b[0] - a[0];
if (diff !== 0) return diff;
return a[1] - b[1];
});
2013-01-31 01:49:25 +08:00
2018-02-25 09:00:20 +08:00
const pair = sortedExtendedPairCombinations[0];
2013-01-31 01:49:25 +08:00
if (pair) {
chunkGraph.integrateChunks(pair[2], pair[3]);
2018-02-25 09:00:20 +08:00
chunks.splice(chunks.indexOf(pair[3]), 1);
return true;
}
2014-02-04 01:12:19 +08:00
}
2018-02-25 09:00:20 +08:00
);
2013-01-31 01:49:25 +08:00
});
}
}
module.exports = LimitChunkCountPlugin;