Skip to content

Commit d3f2927

Browse files
vigneshshanmugamsokra
authored andcommitted
normalize asset size and produce warnings for performance
1 parent cbe2f06 commit d3f2927

2 files changed

Lines changed: 36 additions & 7 deletions

File tree

lib/performance/EmittedAssetSizeLimitPlugin.js

Lines changed: 35 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,16 +11,45 @@ function EmittedAssetSizeLimitPlugin(performanceOptions) {
1111

1212
module.exports = EmittedAssetSizeLimitPlugin;
1313

14+
function normalizeAndCompare(sizeLimit, assetSize) {
15+
// sizeLimit=maxAssetSize is always expressed in kB
16+
// assetSize is expressed in byte size
17+
sizeLimit = sizeLimit * 1024;
18+
console.log(sizeLimit, assetSize);
19+
return sizeLimit < assetSize;
20+
}
21+
22+
function getJSWarnings(noOfAssets, sizeLimit, assetSize) {
23+
var warnings = [];
24+
if(normalizeAndCompare(sizeLimit, assetSize)) {
25+
if(noOfAssets === 1) {
26+
warnings.push(new Error("EmmittedAssetSizeWarning: " + "This asset exceeds " + sizeLimit + "kB. Consider reducing the size for optimal web performance."));
27+
} else {
28+
warnings.push(new Error("EmmittedAssetSizeWarning: " + "Highlighted chunks are large and are likely to impact web performance. Consider keeping total chunks of page < " + sizeLimit + "kB"));
29+
}
30+
}
31+
return warnings;
32+
}
33+
1434
EmittedAssetSizeLimitPlugin.prototype.apply = function(compiler) {
35+
36+
if(!this.hints) {
37+
return;
38+
}
39+
1540
var sizeLimit = this.maxAssetSize;
1641
var hints = this.hints;
17-
compiler.plugin("after-emit", function(compilation, callback) {
18-
for (var asset in compilation.assets) {
19-
if (sizeLimit < compilation.assets[asset].size() && hints) {
20-
compilation.warnings.push(new Error("EmmittedAssetSizeWarning: " + "This asset exceeds " + sizeLimit + "kB. Consider reducing the size for optimal web performance."));
21-
}
22-
}
42+
var jsRegex = /\.js($|\?)/i;
2343

44+
compiler.plugin("after-emit", function(compilation, callback) {
45+
var assets = Object.keys(compilation.assets);
46+
var noOfAssets = assets.length;
47+
assets.forEach(function(file) {
48+
var assetSize = compilation.assets[file].size();
49+
var warnings = jsRegex.test(file) && getJSWarnings(noOfAssets, sizeLimit, assetSize);
50+
Array.prototype.push.apply(compilation.warnings, warnings);
51+
});
2452
callback();
2553
});
54+
2655
};

schemas/webpackOptionsSchema.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -752,7 +752,7 @@
752752
"additionalProperties": false,
753753
"properties": {
754754
"maxAssetSize": {
755-
"description": "Filesize limit (in kb) when exceeded, that webpack will provide performance hints",
755+
"description": "Filesize limit (in kB) when exceeded, that webpack will provide performance hints",
756756
"type": "number"
757757
},
758758
"hints": {

0 commit comments

Comments
 (0)