Skip to content

bundleAnalyzer

Build artifact size analysis plugin with JSON/HTML reports, gzip calculation, threshold alerts, and build comparison.

Import Methods

typescript
// Submodule import (recommended)
import { bundleAnalyzer } from '@meng-xi/vite-plugin/plugins/bundle-analyzer'
import type { BundleAnalyzerOptions, BundleAnalysisResult, BundleOutputFormat } from '@meng-xi/vite-plugin/plugins/bundle-analyzer'

// Barrel import
import { bundleAnalyzer } from '@meng-xi/vite-plugin'

Quick Start

typescript
import { defineConfig } from 'vite'
import { bundleAnalyzer } from '@meng-xi/vite-plugin'

export default defineConfig({
	plugins: [bundleAnalyzer()]
})

Features

  • Multi-format report output: Supports JSON, HTML, or both formats simultaneously
  • Size analysis: Calculates original size and gzip-compressed size
  • Threshold alerts: Automatic alerts for chunks exceeding specified size
  • Build comparison: Compare size changes with historical reports
  • Visual charts: HTML reports support treemap, sunburst, and list views
  • Module ranking: Top N largest modules, distinguishing source from node_modules
  • File type distribution: Size distribution statistics by file extension

Options

OptionTypeDefaultDescription
outputFormat'json' | 'html' | 'both''json'Report output format
outputFilestring'bundle-analysis'Report output filename (without extension)
openAnalyzerbooleanfalseWhether to auto-open browser after HTML report
sizeThresholdnumber100Size alert threshold (KB)
topModulesnumber20Top N largest modules count
compareWithstring | nullnullPath to historical report for comparison
gzipSizebooleantrueWhether to calculate gzip size
excludeNodeModulesbooleanfalseWhether to exclude node_modules modules
excludePatternsstring[][]File path patterns to exclude
includeExtensionsstring[][]File extensions to include, empty for all
defaultChartType'treemap' | 'sunburst' | 'list''treemap'Default chart type in HTML report
enabledbooleantrueEnable the plugin
verbosebooleantrueShow detailed logs
errorStrategy'throw' | 'log' | 'ignore''throw'Error handling strategy

Type Exports

BundleOutputFormat

typescript
type BundleOutputFormat = 'json' | 'html' | 'both'

Report output format type.

BundleAnalysisResult

Analysis result interface with the following fields:

FieldTypeDescription
timestampstringAnalysis timestamp (ISO format)
totalSizenumberTotal build artifact size (bytes)
totalGzipSizenumberTotal gzip size (bytes)
chunksChunkStats[]Chunk statistics list
topModulesModuleStats[]Top N largest modules
fileTypeDistributionFileTypeDistribution[]File type distribution stats
warningsSizeWarning[]Size threshold alert list
comparisonDiffsComparisonDiff[]Build comparison diff list
analysisTimenumberAnalysis duration (ms)

ChunkStats

Statistics for a single chunk:

FieldTypeDescription
namestringChunk name
sizenumberOriginal size (bytes)
gzipSizenumberGzip-compressed size (bytes)
modulesModuleStats[]Included modules list
type'entry' | 'chunk' | 'asset'Chunk type
fileCountnumberNumber of included files

SizeWarning

Size alert information:

FieldTypeDescription
level'module' | 'chunk'Alert level
namestringAlert target name
sizeKBnumberActual size (KB)
thresholdKBnumberThreshold size (KB)
messagestringAlert message

ComparisonDiff

Build comparison diff item:

FieldTypeDescription
namestringModule/chunk name
previousSizenumberPrevious build size
currentSizenumberCurrent build size
diffnumberSize change amount
diffPercentagenumberChange percentage
trend'increased' | 'decreased' | 'unchanged' | 'added' | 'removed'Change trend

Examples

Basic Usage

typescript
bundleAnalyzer()

Generate HTML Visual Report

typescript
bundleAnalyzer({
	outputFormat: 'html',
	openAnalyzer: true
})

Output Both JSON and HTML Reports

typescript
bundleAnalyzer({
	outputFormat: 'both',
	outputFile: 'bundle-report'
})

Set Size Threshold Alerts

typescript
bundleAnalyzer({
	sizeThreshold: 200,
	gzipSize: true
})

Chunks exceeding 200KB will trigger alerts; those exceeding 2x the threshold are marked as critical.

Compare with Historical Build

typescript
bundleAnalyzer({
	compareWith: 'dist/bundle-analysis.json',
	outputFormat: 'json'
})

After the first build generates a report, subsequent builds will automatically compare with the previous results, showing increased, decreased, added, and removed modules.

Exclude Specific Modules

typescript
bundleAnalyzer({
	excludeNodeModules: true,
	excludePatterns: ['vendor', 'polyfill'],
	includeExtensions: ['.js', '.css']
})

Production Only

typescript
bundleAnalyzer({
	enabled: process.env.NODE_ENV === 'production'
})

Log Errors Without Breaking Build

typescript
bundleAnalyzer({
	errorStrategy: 'log'
})

Notes

  • The plugin executes during the writeBundle phase (enforce: 'post'), ensuring analysis runs after all build artifacts are written
  • Gzip size calculation uses the highest compression level (level: 9), which may take longer for large projects; set gzipSize: false to disable
  • Build comparison requires manually saving a JSON report as a baseline first, then specifying the path via compareWith
  • Visual charts in HTML reports depend on inline JavaScript, which may not display correctly under strict CSP policies
  • The openAnalyzer option supports cross-platform: Windows (start), macOS (open), and Linux (xdg-open)

Released under the MIT License.