Webpack plugin and CLI utility that represents bundle content as convenient interactive zoomable treemap
npx @tessl/cli install tessl/npm-webpack-bundle-analyzer@4.10.0Webpack Bundle Analyzer is a plugin and CLI utility that visualizes size of webpack output files with an interactive zoomable treemap. It helps developers analyze bundle composition, identify large modules, find optimization opportunities, and understand what's really inside their webpack bundles.
npm install --save-dev webpack-bundle-analyzerMain exports from the package:
const { BundleAnalyzerPlugin, start } = require('webpack-bundle-analyzer');For CommonJS environments:
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const start = require('webpack-bundle-analyzer').start;Individual module imports for advanced usage:
// Analysis engine
const { getViewerData, readStatsFromFile } = require('webpack-bundle-analyzer/lib/analyzer');
// Report generation
const { generateReport, generateJSONReport, startServer } = require('webpack-bundle-analyzer/lib/viewer');
// Utilities
const { createAssetsFilter, defaultTitle, open } = require('webpack-bundle-analyzer/lib/utils');
const Logger = require('webpack-bundle-analyzer/lib/Logger');const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
module.exports = {
plugins: [
new BundleAnalyzerPlugin()
]
};# Generate webpack stats file first
webpack --profile --json > stats.json
# Analyze the bundle
webpack-bundle-analyzer stats.jsonWebpack Bundle Analyzer consists of several core components:
Primary plugin class for webpack integration, providing configurable bundle analysis during builds with multiple output modes and visualization options.
class BundleAnalyzerPlugin {
constructor(options?: BundleAnalyzerOptions);
apply(compiler: object): void;
}
interface BundleAnalyzerOptions {
analyzerMode?: 'server' | 'static' | 'json' | 'disabled';
analyzerHost?: string;
analyzerPort?: number | 'auto';
analyzerUrl?: (options: { listenHost: string; listenPort: number; boundAddress: object }) => string;
reportFilename?: string;
reportTitle?: string | (() => string);
defaultSizes?: 'stat' | 'parsed' | 'gzip';
openAnalyzer?: boolean;
generateStatsFile?: boolean;
statsFilename?: string;
statsOptions?: object;
excludeAssets?: string | RegExp | ((assetName: string) => boolean) | Array<string | RegExp | ((assetName: string) => boolean)>;
logLevel?: 'info' | 'warn' | 'error' | 'silent';
}Command-line interface for analyzing webpack bundle stats files with flexible output modes and server capabilities.
// CLI Command Format
webpack-bundle-analyzer <bundleStatsFile> [bundleDir] [options]
// Available CLI Options
interface CLIOptions {
mode?: 'server' | 'static' | 'json';
host?: string;
port?: number | 'auto';
report?: string;
title?: string;
defaultSizes?: 'stat' | 'parsed' | 'gzip';
open?: boolean;
exclude?: string[];
logLevel?: 'debug' | 'info' | 'warn' | 'error' | 'silent';
}Legacy function for starting development server with bundle visualization. This is an alias for the startServer function from the viewer module.
/**
* Start HTTP server with interactive bundle visualization (deprecated alias)
* @param bundleStats - Webpack stats object
* @param options - Server configuration options
* @returns Promise resolving to server instance
*/
function start(
bundleStats: object,
options?: ServerOptions
): Promise<ServerInstance>;Note: This function is deprecated. Use the Report Generation capabilities or viewer module directly for new code.
Core analysis engine that processes webpack stats and generates interactive visualizations with multiple size metrics and filtering capabilities.
function getViewerData(
bundleStats: object,
bundleDir: string,
options?: AnalyzerOptions
): BundleInfo[];
interface AnalyzerOptions {
logger?: Logger;
excludeAssets?: string | RegExp | ((assetName: string) => boolean) | Array<string | RegExp | ((assetName: string) => boolean)>;
}
interface BundleInfo {
label: string;
isAsset: boolean;
statSize: number;
parsedSize?: number;
gzipSize?: number;
groups: ChartData[];
isInitialByEntrypoint: { [entrypoint: string]: boolean };
}Static report generation system for creating HTML and JSON reports with customizable output options and browser integration.
function generateReport(
bundleStats: object,
options?: ReportOptions
): Promise<void>;
function generateJSONReport(
bundleStats: object,
options?: JSONReportOptions
): Promise<void>;
interface ReportOptions {
openBrowser?: boolean;
reportFilename: string;
reportTitle?: string | (() => string);
bundleDir?: string;
logger?: Logger;
defaultSizes?: 'stat' | 'parsed' | 'gzip';
excludeAssets?: string | RegExp | ((assetName: string) => boolean) | Array<string | RegExp | ((assetName: string) => boolean)>;
}
interface JSONReportOptions {
reportFilename: string;
bundleDir?: string;
logger?: Logger;
excludeAssets?: string | RegExp | ((assetName: string) => boolean) | Array<string | RegExp | ((assetName: string) => boolean)>;
}Core utility functions for advanced usage scenarios and custom integrations.
/**
* Creates asset filter function from exclude patterns
* @param excludePatterns - Pattern or array of patterns to exclude assets
* @returns Filter function that returns true for included assets
*/
function createAssetsFilter(
excludePatterns: string | RegExp | ((assetName: string) => boolean) | Array<string | RegExp | ((assetName: string) => boolean)>
): (assetName: string) => boolean;
/**
* Default title generation function
* @returns Formatted title with current date and time
*/
function defaultTitle(): string;
/**
* Default analyzer URL generation function
* @param options - Server address options
* @returns Complete URL for server mode
*/
function defaultAnalyzerUrl(options: { listenHost: string; boundAddress: { port: number } }): string;
/**
* Opens URL in default browser with error handling
* @param uri - URL to open
* @param logger - Logger for error messages
*/
function open(uri: string, logger: Logger): void;
/**
* Parse webpack bundle file to extract module information
* @param bundlePath - Path to bundle file
* @returns Bundle parsing result with modules and runtime info
*/
function parseBundle(bundlePath: string): {
src: string;
runtimeSrc: string;
modules: { [moduleId: string]: string };
};
/**
* Write webpack stats to file with streaming
* @param stats - Webpack stats object
* @param filepath - Output file path
* @returns Promise that completes when file is written
*/
function writeStats(stats: object, filepath: string): Promise<void>;Configurable logging system with multiple log levels and console output.
class Logger {
static levels: string[];
static defaultLevel: string;
constructor(level?: string);
setLogLevel(level: string): void;
debug(...args: any[]): void;
info(...args: any[]): void;
warn(...args: any[]): void;
error(...args: any[]): void;
}// Size Types
type SizeType = 'stat' | 'parsed' | 'gzip';
// Analyzer Modes
type AnalyzerMode = 'server' | 'static' | 'json' | 'disabled';
// Log Levels
type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'silent';
// Asset Filter Pattern
type AssetFilterPattern =
| string
| RegExp
| ((assetName: string) => boolean);
// Chart Data Structure
interface ChartData {
label: string;
value: number;
children?: ChartData[];
}
// Logger Interface
interface Logger {
/** Available log levels */
static levels: string[];
/** Default log level */
static defaultLevel: string;
/** Current active log levels */
activeLevels: Set<string>;
/** Set the logging level */
setLogLevel(level: LogLevel): void;
/** Log debug messages */
debug(...args: any[]): void;
/** Log informational messages */
info(...args: any[]): void;
/** Log warning messages */
warn(...args: any[]): void;
/** Log error messages */
error(...args: any[]): void;
}
// Bundle Parsing Result
interface BundleParseResult {
/** Complete bundle source code */
src: string;
/** Runtime/entry source code */
runtimeSrc: string;
/** Map of module IDs to their source code */
modules: { [moduleId: string]: string };
}