This is a great request for a custom Webpack plugin. I need to create a plugin that:
- Analyzes build assets
- Fails the build if any JavaScript chunk exceeds 200KB gzipped
- Outputs a JSON report showing which dependencies contribute most to the bloat
Let me break down what needs to be done:
- Create a Webpack plugin class that hooks into the compilation process
- Get all assets after compilation
- Filter for JavaScript files
- Calculate gzip size for each
- Identify chunks that exceed the threshold
- Analyze which dependencies contribute to the bloat
- Generate a JSON report
- Fail the build if threshold is exceeded
I'll need to:
- Use zlib for gzip compression
- Use webpack's compiler hooks
- Potentially use source-map or webpack's module analysis
- Calculate sizes accurately
Here's what I'll create:
- The main plugin class
- Helper functions for analyzing dependencies
- Usage examples
- Configuration options
- Output report format
Let me write comprehensive code:
const fs = require('fs');
const path = require('path');
const zlib = require('zlib');
const { promisify } = require('util');
const gzip = promisify(zlib.gzip);
class BundleSizeAnalyzerPlugin {
constructor(options = {}) {
this.threshold = options.threshold || 200; // KB
this.outputPath = options.outputPath || './bundle-report.json';
this.failOnExceed = options.failOnExceed !== false;
this.analyzeChunks = options.analyzeChunks !== false;
this.excludePatterns = options.excludePatterns || [];
}
apply(compiler) {
compiler.hooks.afterEmit.tapPromise(
'BundleSizeAnalyzerPlugin',
async (compilation) => {
await this.analyze(compilation, compiler);
}
);
}
async analyze(compilation, compiler) {
const assets = compilation.assets;
const report = {
timestamp: new Date().toISOString(),
threshold: `${this.threshold}KB`,
chunks: [],
summary: {
totalAssets: 0,
exceededChunks: 0,
totalGzipped: 0,
},
dependencies: {},
};
const exceededChunks = [];
// Analyze each asset
for (const [filename, asset] of Object.entries(assets))
{
if (!filename.endsWith('.js')) continue;
if (this.shouldExclude(filename)) continue;
try {
const source = asset.source();
const gzipSize = await this.getGzipSize(source);
const gzipSizeKB = (gzipSize / 1024).toFixed(2);
const rawSize = (source.length / 1024).toFixed(2);
const chunk = {
filename,
rawSize: `${rawSize}KB`,
gzipSize: `${gzipSizeKB}KB`,
exceeded: gzipSize > this.threshold * 1024,
};
report.chunks.push(chunk);
report.summary.totalAssets++;
report.summary.totalGzipped += gzipSize;
if (chunk.exceeded) {
exceededChunks.push(chunk);
report.summary.exceededChunks++;
}
} catch (error) {
console.error(`Error analyzing ${filename}:`, error);
}
}
// Analyze dependencies if available
if (this.analyzeChunks) {
report
.dependencies = this.analyzeDependencies(compilation);
}
// Format total size
report.summary.totalGzipped = `${(report.summary.totalGzipped / 1024).toFixed(2)}KB`;
// Write report
this.writeReport(report);
// Fail build if needed
if (this.failOnExceed && exceededChunks.length > 0) {
this.logWarnings(exceededChunks);
throw new Error(
`Bundle exceeds size limit! ${exceededChunks.length} chunk(s) exceeded ${this.threshold}KB limit:\n` +
exceededChunks.map(c => ` - ${c.filename}: ${c.gzipSize}`).join('\n')
);
} else if (exceededChunks.length > 0) {
this.logWarnings(exceededChunks);
} else {
console.log(`✓ All chunks are within ${this.threshold}KB limit!`);
}
}
After collecting chunk data, I need to optionally pull in dependency information if that analysis is enabled. Then I convert the total gzipped size to KB format and persist the report. Finally, I check whether the build should fail based on whether any chunks exceeded the threshold—if so, I throw an error with details about which chunks went over; otherwise I log a success message or warnings as appropriate. d = await gzip(buffer);
return compressed.length;
}
writeReport(report) {
const reportPath = path.resolve(this.outputPath);
const reportDir = path.dirname(reportPath);
if (!fs.existsSync(reportDir)) {
fs.mkdirSync(reportDir, { recursive: true });
}
fs.writeFileSync(reportPath, JSON.stringify(report, null, 2));
console.log(`\n📊 Bundle size report written to: ${reportPath}`);
}
shouldExclude(filename) {
return this.excludePatterns.some(pattern => {
if (pattern instanceof RegExp) {
return pattern.test(filename);
}
return filename.includes(pattern);
});
}
logWarnings(exce
I cannot complete this thought as the next thinking is incomplete. I need to build out a more comprehensive bundle analysis solution that goes beyond the basic plugin. Let me set up the core utilities and dependency tracking first, starting with the necessary imports and helper functions for gzip compression analysis and file system operations.</think>
# Custom Webpack Bundle Size Analyzer Plugin
Here's a comprehensive solution with a custom Webpack plugin that analyzes bundle sizes and generates detailed reports:
## Main Plugin
```javascript
// BundleSizeAnalyzerPlugin.js
const fs = require('fs');
const path = require('path');
const zlib = require('zlib');
const { promisify } = require('util');
const gzip = promisify(zlib.gzip);
class BundleSizeAnalyzerPlugin {
constructor(options = {}) {
this.threshold = options.threshold || 200; // KB
this.outputPath = options.outputPath || './bundle-report.json';
this.failOnExceed = options.failOnExceed !== false;
this.analyzeModules = options.analyzeModules !== false;
this.excludePatterns = options.excludePatterns || [];
this.verbose = options.verbose || false;
}
apply(compiler) {
compiler.hooks.afterEmit.tapPromise(
'BundleSizeAnalyzerPlugin',
async (compilation) => {
try {
const report = await this.analyze(compilation);
this.writeReport(report);
if (this.failOnExceed && report.failed) {
throw new Error(report.errorMessage);
}
} catch (error) {
if (this.failOnExceed) {
throw error;
} else {
console.error('Bundle analysis error:', error.message);
}
}
}
);
}
async analyze(compilation) {
const assets = compilation.assets;
const chunks = [];
const exceededChunks = [];
let totalGzipped = 0;
// Analyze each JavaScript asset
for (const [filename, asset] of Object.entries(assets)) {
if (!filename.endsWith('.js')) continue;
if (this.shouldExclude(filename)) continue;
try {
const source = asset.source();
const { raw, gzip: gzipSize } = await this.calculateSizes(source);
const gzipSizeKB = gzipSize / 1024;
const rawSizeKB = raw / 1024;
const chunkInfo = {
filename,
rawSize: rawSizeKB,
rawSizeFormatted: `${rawSizeKB.toFixed(2)}KB`,
gzipSize: gzipSizeKB,
gzipSizeFormatted: `${gzipSizeKB.toFixed(2)}KB`,
ratio: (gzipSize / raw * 100).toFixed(1),
exceeded: gzipSize > this.threshold * 1024,
};
chunks.push(chunkInfo);
totalGzipped += gzipSize;
if (chunkInfo.exceeded) {
exceededChunks.push(chunkInfo);
}
if (this.verbose) {
const status = chunkInfo.exceeded ? '❌' : '✓';
console.log(
`${status} ${filename}: ${chunkInfo.gzipSizeFormatted} (gzip)`
);
}
} catch (error) {
console.error(`Error analyzing ${filename}:`, error);
}
}
// Sort chunks by gzip size (largest first)
chunks.sort((a, b) => b.gzipSize - a.gzipSize);
const report = {
timestamp: new Date().toISOString(),
configuration: {
threshold: `${this.threshold}KB`,
},
summary: {
totalChunks: chunks.length,
exceededChunks: exceededChunks.length,
totalGzipped: `${(totalGzipped / 1024).toFixed(2)}KB`,
totalGzippedBytes: totalGzipped,
passed: exceededChunks.length === 0,
},
chunks,
topOffenders: exceededChunks.sort((a, b) => b.gzipSize - a.gzipSize),
failed: exceededChunks.length > 0,
};
// Analyze module dependencies if enabled
if (this.analyzeModules) {
report.dependencies = this.analyzeDependencies(
compilation,
exceededChunks
);
}
if (exceededChunks.length > 0) {
report.errorMessage = this.buildErrorMessage(exceededChunks);
}
this.logSummary(report);
return report;
}
async calculateSizes(source) {
const buffer = typeof source === 'string'
? Buffer.from(source, 'utf8')
: source;
const gzipped = await gzip(buffer, { level: 9 });
return {
raw: buffer.length,
gzip: gzipped.length,
};
}
analyzeDependencies(compilation, exceededChunks) {
const dependencies = new Map();
const sourceMap = new Map();
// Parse module graph
compilation.chunkGraph.getChunkModules(
compilation.chunks[0]
).forEach(module => {
if (!module.resource) return;
const modulePath = module.resource;
const isNodeModule = modulePath.includes('node_modules');
if (!isNodeModule) return;
// Extract package name
const match = modulePath.match(/node_modules[\\/](@[^\\/]+[\\/])?([^\\/]+)/);
if (!match) return;
const packageName = match[1]
? `${match[1]}${match[2]}`
: match[2];
const size = module.size('javascript') || 0;
if (!dependencies.has(packageName)) {
dependencies.set(packageName, {
size: 0,
modules: [],
mainModules: [],
});
}
const dep = dependencies.get(packageName);
dep.size += size;
dep.modules.push({
path: modulePath.replace(process.cwd(), ''),
size,
});
// Track which chunks these dependencies belong to
compilation.chunkGraph.getModuleChunks(module).forEach(chunk => {
exceededChunks.forEach(exceeded => {
if (exceeded.filename.includes(chunk.name || chunk.id)) {
if (!sourceMap.has(packageName)) {
sourceMap.set(packageName, []);
}
sourceMap.get(packageName).push(exceeded.filename);
}
});
});
});
// Convert to sorted array and format
const sorted = Array.from(dependencies.entries())
.sort(([, a], [, b]) => b.size - a.size)
.slice(0, 30);
const result = {};
sorted.forEach(([name, data]) => {
const chunks = sourceMap.get(name) || [];
result[name] = {
size: `${(data.size / 1024).toFixed(2)}KB`,
sizeBytes: data.size,
moduleCount: data.modules.length,
topModules: data.modules
.sort((a, b) => b.size - a.size)
.slice(0, 3)
.map(m => ({
path: m.path,
size: `${(m.size / 1024).toFixed(2)}KB`,
})),
appearsIn: chunks,
};
});
return result;
}
buildErrorMessage(exceededChunks) {
const lines = [
'\n❌ BUNDLE SIZE LIMIT EXCEEDED\n',
`Threshold: 200KB (gzipped)`,
`Exceeded chunks: ${exceededChunks.length}\n`,
'Offending chunks:',
];
exceededChunks
.sort((a, b) => b.gzipSize - a.gzipSize)
.forEach(chunk => {
const excess = ((chunk.gzipSize - 200) / 1024).toFixed(2);
lines.push(` • ${chunk.filename}: ${chunk.gzipSizeFormatted} (+${excess}MB)`);
});
return lines.join('\n');
}
logSummary(report) {
console.log('\n' + '='.repeat(60));
console.log('📊 BUNDLE SIZE ANALYSIS REPORT');
console.log('='.repeat(60));
console.log(`
Threshold: ${report.configuration.threshold}
Total Chunks: ${report.summary.totalChunks}
Total Size: ${report.summary.totalGzipped}
Exceeded Chunks: ${report.summary.exceededChunks}
Status: ${report.summary.passed ? '✅ PASSED' : '❌ FAILED'}
`);
if (report.summary.exceededChunks > 0) {
console.log('Top Offenders:');
report.topOffenders.slice(0, 5).forEach(chunk => {
const excess = (chunk.gzipSize / 1024 - 200).toFixed(2);
console.log(
` ❌ ${chunk.filename.padEnd(30)} ${chunk.gzipSizeFormatted.padEnd(10)} (+${excess}MB over limit)`
);
});
} else {
console.log('Top Chunks:');
report.chunks.slice(0, 5).forEach(chunk => {
console.log(
` ✓ ${chunk.filename.padEnd(30)} ${chunk.gzipSizeFormatted.padEnd(10)}`
);
});
}
console.log('='.repeat(60) + '\n');
}
writeReport(report) {
const reportPath = path.resolve(this.outputPath);
const reportDir = path.dirname(reportPath);
if (!fs.existsSync(reportDir)) {
fs.mkdirSync(reportDir, { recursive: true });
}
fs.writeFileSync(
reportPath,
JSON.stringify(report, null, 2)
);
console.log(`📈 Report saved to: ${reportPath}`);
}
shouldExclude(filename) {
return this.excludePatterns.some(pattern => {
if (pattern instanceof RegExp) {
return pattern.test(filename);
}
return filename.includes(pattern);
});
}
}
module.exports = BundleSizeAnalyzerPlugin;
Webpack Configuration
// webpack.config.js
const BundleSizeAnalyzerPlugin = require('./BundleSizeAnalyzerPlugin');
module.exports = {
mode: 'production',
entry: './src/index.js',
output: {
path: __dirname + '/dist',
filename: '[name].[contenthash:8].js',
chunkFilename: '[name].[contenthash:8].chunk.js',
},
optimization: {
splitChunks: {
chunks: 'all',
minSize: 20000,
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendor',
reuseExistingChunk: true,
},
},
},
},
plugins: [
new BundleSizeAnalyzerPlugin({
threshold: 200, // KB
outputPath: './reports/bundle-analysis.json',
failOnExceed: true,
analyzeModules: true,
verbose: true,
excludePatterns: [
/\.map\.js$/,
'polyfills',
],
}),
],
};
Report Analysis Utility
// analyze-report.js
const fs = require('fs');
const path = require('path');
class ReportAnalyzer {
constructor(reportPath) {
this.report = JSON.parse(
fs.readFileSync(reportPath, 'utf-8')
);
}
static fromFile(reportPath) {
return new ReportAnalyzer(reportPath);
}
printDetailedReport() {
const { report } = this;
console.log('\n📋 DETAILED BUNDLE ANALYSIS\n');
// Dependencies contribution
if (report.dependencies && Object.keys(report.dependencies).length > 0) {
console.log('🔴 TOP DEPENDENCIES BY SIZE:\n');
Object.entries(report.dependencies)
.slice(0, 20)
.forEach(([name, data]) => {
console.log(`\n 📦 ${name}`);
console.log(` Size: ${data.size}`);
console.log(` Modules: ${data.moduleCount}`);
if (data.topModules.length > 0) {
console.log(' Top modules:');
data.topModules.forEach(mod => {
console.log(` • ${mod.path} (${mod.size})`);
});
}
if (data.appearsIn.length > 0) {
console.log(` Appears in: ${data.appearsIn.join(', ')}`);
}
});
}
// Size comparison
console.log('\n📊 SIZE DISTRIBUTION:\n');
const chunks = report.chunks.sort((a, b) => b.gzipSize - a.gzipSize);
chunks.forEach(chunk => {
const percentage = (chunk.gzipSize / report.summary.totalGzippedBytes * 100).toFixed(1);
const bar = '█'.repeat(Math.round(percentage / 2));
console.log(
` ${chunk.filename.padEnd(30)} ${chunk.gzipSizeFormatted.padEnd(10)} ` +
`${bar} ${percentage}%`
);
});
// Recommendations
if (report.topOffenders.length > 0) {
console.log('\n💡 OPTIMIZATION RECOMMENDATIONS:\n');
this.printRecommendations();
}
}
printRecommendations() {
const { report } = this;
const recommendations = [];
// Check for large dependencies
if (report.dependencies) {
Object.entries(report.dependencies)
.slice(0, 10)
.forEach(([name, data]) => {
if (parseFloat(data.size) > 50) {
recommendations.push(
` • Consider replacing "${name}" with a lighter alternative ` +
`(currently ${data.size})`
);
}
});
}
// Check for large chunks
if (report.topOffenders.length > 0) {
recommendations.push(
` • Split large chunks using dynamic imports`
);
recommendations.push(
` • Enable code minification and tree-shaking`
);
recommendations.push(
` • Use compression middleware on your server`
);
}
console.log(recommendations.join('\n'));
}
compareReports(previousReportPath) {
const previous = JSON.parse(
fs.readFileSync(previousReportPath, 'utf-8')
);
const current = this.report;
const currentSize = current.summary.totalGzippedBytes;
const previousSize = previous.summary.totalGzippedBytes;
const diff = currentSize - previousSize;
const percentChange = ((diff / previousSize) * 100).toFixed(2);
console.log('\n📈 BUILD COMPARISON\n');
console.log(`Previous: ${(previousSize / 1024).toFixed(2)}KB`);
console.log(`Current: ${(currentSize / 1024).toFixed(2)}KB`);
console.log(
`Change: ${diff > 0 ? '+' : ''}${(diff / 1024).toFixed(2)}KB ` +
`(${percentChange}%) ${diff > 0 ? '⬆️' : '⬇️'}`
);
}
}
module.exports = ReportAnalyzer;
// CLI usage
if (require.main === module) {
const reportPath = process.argv[2] || './bundle-report.json';
const compareWith = process.argv[3];
const analyzer = ReportAnalyzer.fromFile(reportPath);
analyzer.printDetailedReport();
if (compareWith) {
analyzer.compareReports(compareWith);
}
}
Package.json Scripts
{
"scripts": {
"build": "webpack --mode production",
"analyze": "node analyze-report.js reports/bundle-analysis.json",
"analyze:compare": "node analyze-report.js reports/bundle-analysis.json reports/bundle-analysis.previous.json"
}
}
Example Output
============================================================
📊 BUNDLE SIZE ANALYSIS REPORT
============================================================
Threshold: 200KB
Total Chunks: 5
Total Size: 450.23KB
Exceeded Chunks: 2
Status: ❌ FAILED
Top Offenders:
❌ main.a1b2c3d4.js 320.50KB (+120.50MB over limit)
❌ vendor.e5f6g7h8.js 225.75KB (+25.75MB over limit)
✓ utils.i9j0k1l2.js 45.32KB
✓ polyfills.m3n4o5p6.js 32.18KB
✓ runtime.q7r8s9t0.js 18.22KB
============================================================
Key Features
✅ Accurate Gzip Compression - Uses real gzip compression (level 9)
✅ Dependency Analysis - Shows which packages contribute to bloat
✅ Detailed Reports - JSON output with all metrics
✅ Build Failure - Optional build failure on threshold exceed
✅ Comparison - Compare builds over time
✅ Flexible Configuration - Customizable thresholds and exclusions
✅ Verbose Logging - Optional detailed console output
✅ Top Offenders - Identifies and highlights problem chunks
This solution provides enterprise-grade bundle analysis for your production builds!