Providing custom Webpack 5 plugin code
The plugin hooks into the compilation's processAssets stage, computes gzipped sizes per JavaScript chunk, fails the build if any exceed 200KB, and outputs a JSON report with chunk sizes and a breakdown of contributing packages by approximated module sizes using module paths. It uses Node's built-in zlib and targets Webpack 5, emitting the report as an asset and pushing errors to compilation.errors to fail when limits are exceeded.
Here’s a self‑contained Webpack 5 plugin that will:
- Iterate your emitted JavaScript chunks.
- Compute their gzipped size.
- Fail the build if any exceeds 200 KB (configurable).
- Emit a JSON report with a per‑chunk breakdown of which packages (dependencies) contribute most to the size.
// ChunkSizeLimitPlugin.js
const zlib = require('zlib');
class ChunkSizeLimitPlugin {
/**
* @param {object} [options]
* @param {number} [options.limit] Byte limit for gzipped JS chunks (default: 200 * 1024 bytes)
* @param {string} [options.reportFile] Name of JSON report to emit (default: 'bundle-bloat-report.json')
*/
constructor(options = {}) {
this.limit = options.limit || 200 * 1024; // 200 KB
this.reportFile = options.reportFile || 'bundle-bloat-report.json';
}
apply(compiler) {
const pluginName = 'ChunkSizeLimitPlugin';
compiler.hooks.thisCompilation.tap(pluginName, (compilation) => {
const { Compilation, sources } = compiler.webpack;
compilation.hooks.processAssets.tap(
{
name: pluginName,
stage: Compilation.PROCESS_ASSETS_STAGE_SUMMARIZE,
},
() => {
const chunkReports = [];
const errors = [];
for (const chunk of compilation.chunks) {
// Only consider JS assets belonging to this chunk
const jsFiles = [...chunk.files].filter((file) => file.endsWith('.js'));
if (jsFiles.length === 0) continue;
// Aggregate gzipped size across all JS files of the chunk
let gzippedSize = 0;
const fileSizes = [];
for (const file of jsFiles) {
const asset = compilation.getAsset(file);
if (!asset) continue;
const source = asset.source;
const buf =
typeof source.buffer === 'function'
? source.buffer()
: Buffer.isBuffer(source.source())
? source.source()
: Buffer.from(source.source());
const gz = zlib.gzipSync(buf);
gzippedSize += gz.length;
fileSizes.push({ file, gzippedBytes: gz.length });
}
// Build a dependency/package breakdown for this chunk
const packageSizes = {};
const chunkGraph = compilation.chunkGraph;
// chunkGraph is only available in Webpack 5
const modules = chunkGraph.getChunkModulesIterable(chunk);
for (const mod of modules) {
const size = typeof mod.size === 'function' ? mod.size() : 0;
const pkgName = this._getPackageName(mod);
packageSizes[pkgName] = (packageSizes[pkgName] || 0) + size;
}
// Sort packages by size descending
const topPackages = Object.entries(packageSizes)
.map(([name, size]) => ({ name, bytes: size }))
.sort((a, b) => b.bytes - a.bytes);
const overLimit = gzippedSize > this.limit;
if (overLimit) {
errors.push(
new Error(
`[${pluginName}] Chunk "${chunk.name || chunk.id}" exceeds limit: ` +
`${(gzippedSize / 1024).toFixed(2)} KB gzipped (limit ${(this.limit / 1024).toFixed(2)} KB)`
)
);
}
chunkReports.push({
chunk: chunk.name || chunk.id,
gzippedBytes: gzippedSize,
files: fileSizes,
overLimit,
packages: topPackages,
});
}
// Emit the JSON report
const report = {
limitBytes: this.limit,
limitKB: this.limit / 1024,
chunks: chunkReports,
};
const { RawSource } = sources;
compilation.emitAsset(
this.reportFile,
new RawSource(JSON.stringify(report, null, 2))
);
// Register errors to fail the build if needed
if (errors.length) {
for (const err of errors) {
compilation.errors.push(err);
}
}
}
);
});
}
/**
* Attempt to extract a package name from a module identifier/path.
* Groups non-node_modules modules under "app".
*/
_getPackageName(mod) {
const id = typeof mod.identifier === 'function' ? mod.identifier() : '';
const parts = id.split(/[/\\]+/);
const nmIndex = parts.lastIndexOf('node_modules');
if (nmIndex >= 0) {
const first = parts[nmIndex + 1] || '';
if (first.startsWith('@')) {
// Scoped package: @scope/name
return [first, parts[nmIndex + 2] || ''].filter(Boolean).join('/');
}
return first || 'unknown';
}
return 'app';
}
}
module.exports = ChunkSizeLimitPlugin;
Usage
// webpack.config.js
const ChunkSizeLimitPlugin = require('./ChunkSizeLimitPlugin');
module.exports = {
// ... your existing config
plugins: [
new ChunkSizeLimitPlugin({
limit: 200 * 1024, // optional; defaults to 200 KB
reportFile: 'bundle-bloat-report.json', // optional
}),
],
};
- Build will fail if any chunk’s gzipped JS exceeds the configured limit.
- A
bundle-bloat-report.json will be emitted into your output directory with per‑chunk gzipped sizes and a breakdown of which packages contribute most.