webpack/lib/optimize/LimitChunkCountPlugin.js

56 lines
1.6 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
*/
function LimitChunkCountPlugin(options) {
if(options !== undefined && typeof options !== "object" || Array.isArray(options)) {
throw new Error("Argument should be an options object.\nFor more info on options, see http://webpack.github.io/docs/list-of-plugins.html");
}
2013-01-31 01:49:25 +08:00
this.options = options || {};
}
module.exports = LimitChunkCountPlugin;
LimitChunkCountPlugin.prototype.apply = function(compiler) {
var options = this.options;
compiler.plugin("compilation", function(compilation) {
compilation.plugin("optimize-chunks", function(chunks) {
var maxChunks = options.maxChunks;
if(!maxChunks) return;
if(maxChunks < 1) return;
if(chunks.length <= maxChunks) return;
2013-01-31 01:49:25 +08:00
if(chunks.length > maxChunks) {
2013-01-31 01:49:25 +08:00
var combinations = [];
chunks.forEach(function(a, idx) {
for(var i = 0; i < idx; i++) {
2013-01-31 01:49:25 +08:00
var b = chunks[i];
combinations.push([b, a]);
}
});
combinations.forEach(function(pair) {
2013-06-18 00:55:11 +08:00
var a = pair[0].size(options);
var b = pair[1].size(options);
var ab = pair[0].integratedSize(pair[1], options);
2013-01-31 01:49:25 +08:00
pair.unshift(a + b - ab, ab);
});
2014-02-04 01:12:19 +08:00
combinations = combinations.filter(function(pair) {
return pair[1] !== false;
});
2015-04-24 05:55:50 +08:00
combinations.sort(function(a, b) {
2013-01-31 01:49:25 +08:00
var diff = b[0] - a[0];
if(diff !== 0) return diff;
2013-01-31 01:49:25 +08:00
return a[1] - b[1];
});
var pair = combinations[0];
if(pair && pair[2].integrate(pair[3], "limit")) {
2014-02-04 01:12:19 +08:00
chunks.splice(chunks.indexOf(pair[3]), 1);
this.restartApplyPlugins();
}
2013-01-31 01:49:25 +08:00
}
});
});
};