CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-webpack-bundle-analyzer

Webpack plugin and CLI utility that represents bundle content as convenient interactive zoomable treemap

Overall
score

98%

Overview
Eval results
Files

analysis-engine.mddocs/

Analysis Engine

The analysis engine is the core component that processes webpack stats files and generates visualization data. It handles bundle parsing, module extraction, size calculation, and data transformation for the interactive treemap visualization.

Capabilities

Bundle Data Analysis

Extract and process webpack bundle statistics to generate visualization data.

/**
 * Processes webpack bundle stats and generates viewer data
 * @param bundleStats - Webpack stats object from stats.toJson()
 * @param bundleDir - Directory containing bundle files for parsing
 * @param options - Analysis configuration options
 * @returns Array of bundle information for visualization
 */
function getViewerData(
  bundleStats: object,
  bundleDir: string,
  options?: AnalyzerOptions
): BundleInfo[];

interface AnalyzerOptions {
  /** Logger instance for output messages */
  logger?: Logger;
  /** Patterns to exclude assets from analysis */
  excludeAssets?: string | RegExp | ((assetName: string) => boolean) | Array<string | RegExp | ((assetName: string) => boolean)>;
}

interface BundleInfo {
  /** Bundle filename */
  label: string;
  /** Indicates this is a webpack asset */
  isAsset: boolean;
  /** Original size from webpack stats */
  statSize: number;
  /** Parsed size from actual bundle file */
  parsedSize?: number;
  /** Gzipped size of parsed bundle */
  gzipSize?: number;
  /** Hierarchical module data for treemap visualization */
  groups: ChartData[];
  /** Mapping of entrypoints where this bundle is initial */
  isInitialByEntrypoint: { [entrypoint: string]: boolean };
}

Usage Examples:

const { getViewerData } = require('webpack-bundle-analyzer/lib/analyzer');
const fs = require('fs');

// Load webpack stats
const stats = JSON.parse(fs.readFileSync('stats.json'));

// Basic analysis
const bundleData = getViewerData(stats, './dist');

// With custom logger and asset exclusion
const Logger = require('webpack-bundle-analyzer/lib/Logger');
const logger = new Logger('info');

const bundleData = getViewerData(stats, './dist', {
  logger,
  excludeAssets: /\.css$/
});

Stats File Reading

Read and parse webpack stats JSON files with streaming support for large files.

/**
 * Reads webpack stats from JSON file with streaming parser
 * @param filename - Path to webpack stats JSON file
 * @returns Promise resolving to parsed stats object
 */
function readStatsFromFile(filename: string): Promise<object>;

Usage Examples:

const { readStatsFromFile } = require('webpack-bundle-analyzer/lib/analyzer');

// Read stats file
const stats = await readStatsFromFile('./webpack-stats.json');

// Use with analysis
const bundleData = getViewerData(stats, './dist');

Chart Data Structure

Hierarchical data structure representing module organization for treemap visualization.

interface ChartData {
  /** Display label for the module or folder */
  label: string;
  /** Size value for this node */
  value: number;
  /** Child nodes for nested structure */
  children?: ChartData[];
  /** Additional metadata */
  [key: string]: any;
}

Module Tree Processing

The analysis engine processes webpack modules into a hierarchical tree structure based on file paths and module organization.

Tree Building Process:

  1. Module Extraction: Extract all modules from webpack chunks
  2. Path Parsing: Parse module identifiers into folder/file structures
  3. Tree Construction: Build hierarchical folder tree with modules as leaves
  4. Size Calculation: Calculate sizes at each tree level (stat, parsed, gzip)
  5. Chart Data Generation: Convert tree to visualization-ready format

Module Types Handled:

  • Regular modules with file paths
  • Concatenated modules (webpack optimization)
  • Entry modules at bundle boundaries
  • Runtime modules (filtered out)
  • Child chunk modules

Asset Filtering

Flexible asset filtering system supporting multiple pattern types and combinations.

// Asset filter function signature
type AssetFilter = (assetName: string) => boolean;

// Supported pattern types
type FilterPattern = 
  | string                          // Converted to RegExp
  | RegExp                         // Direct pattern matching
  | ((assetName: string) => boolean); // Custom filter function

// Create filter from patterns
function createAssetsFilter(
  excludePatterns: FilterPattern | FilterPattern[]
): AssetFilter;

Usage Examples:

const { createAssetsFilter } = require('webpack-bundle-analyzer/lib/utils');

// String pattern (converted to RegExp)
const filter1 = createAssetsFilter('vendor');

// RegExp pattern
const filter2 = createAssetsFilter(/\.(css|png|jpg)$/);

// Custom function
const filter3 = createAssetsFilter((assetName) => 
  assetName.includes('legacy') || assetName.startsWith('polyfill')
);

// Multiple patterns
const filter4 = createAssetsFilter([
  'vendor',
  /\.css$/,
  (name) => name.includes('test')
]);

// Use with analysis
const bundleData = getViewerData(stats, './dist', {
  excludeAssets: filter4
});

Size Metrics

Multiple size metrics provide different perspectives on bundle composition.

interface SizeMetrics {
  /** Original size from webpack stats (before minification) */
  statSize: number;
  /** Actual parsed bundle size (after minification) */
  parsedSize?: number;
  /** Gzipped size of parsed bundle */
  gzipSize?: number;
}

type SizeType = 'stat' | 'parsed' | 'gzip';

Size Calculation Details:

  • Stat Size: Taken directly from webpack stats object, represents source sizes
  • Parsed Size: Calculated by parsing actual bundle files, reflects build output
  • Gzip Size: Computed by gzipping parsed bundle content, shows transfer size

Bundle Processing Pipeline

The analysis engine follows a structured pipeline for processing webpack stats:

  1. Stats Validation: Validate webpack stats structure and format
  2. Asset Discovery: Identify JavaScript assets with chunks
  3. Bundle Parsing: Parse bundle files to extract module sources (if bundleDir provided)
  4. Module Processing: Extract modules from chunks and organize by assets
  5. Tree Construction: Build hierarchical module trees for each asset
  6. Size Calculation: Calculate all size metrics (stat, parsed, gzip)
  7. Data Transformation: Convert to visualization-ready format
  8. Entrypoint Mapping: Map assets to webpack entrypoints

Error Handling

Robust error handling for common analysis scenarios.

Common Error Scenarios:

  • Missing bundle files (bundleDir specified but files don't exist)
  • Malformed webpack stats structure
  • Unparseable bundle files (minified with unsupported patterns)
  • Memory filesystem usage (no physical bundle files)

Error Recovery:

  • Falls back to stats-only analysis when bundle parsing fails
  • Continues processing other assets when individual bundles fail
  • Provides informative warnings for missing or problematic files
  • Gracefully handles development vs production scenarios

Usage Examples:

const { getViewerData } = require('webpack-bundle-analyzer/lib/analyzer');
const Logger = require('webpack-bundle-analyzer/lib/Logger');

const logger = new Logger('info');

try {
  // Analysis with potential bundle file issues
  const bundleData = getViewerData(stats, './dist', { logger });
  
  if (!bundleData || bundleData.length === 0) {
    console.log('No JavaScript bundles found in stats');
  }
} catch (error) {
  console.error('Analysis failed:', error.message);
}

Install with Tessl CLI

npx tessl i tessl/npm-webpack-bundle-analyzer

docs

analysis-engine.md

cli-tool.md

index.md

report-generation.md

webpack-plugin.md

tile.json