or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

analysis-engine.mdcli-tool.mdindex.mdreport-generation.mdwebpack-plugin.md

index.mddocs/

0

# Webpack Bundle Analyzer

1

2

Webpack 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.

3

4

## Package Information

5

6

- **Package Name**: webpack-bundle-analyzer

7

- **Package Type**: npm

8

- **Language**: JavaScript

9

- **Installation**: `npm install --save-dev webpack-bundle-analyzer`

10

11

## Core Imports

12

13

Main exports from the package:

14

15

```javascript

16

const { BundleAnalyzerPlugin, start } = require('webpack-bundle-analyzer');

17

```

18

19

For CommonJS environments:

20

21

```javascript

22

const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

23

const start = require('webpack-bundle-analyzer').start;

24

```

25

26

Individual module imports for advanced usage:

27

28

```javascript

29

// Analysis engine

30

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

31

32

// Report generation

33

const { generateReport, generateJSONReport, startServer } = require('webpack-bundle-analyzer/lib/viewer');

34

35

// Utilities

36

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

37

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

38

```

39

40

## Basic Usage

41

42

### As Webpack Plugin

43

44

```javascript

45

const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');

46

47

module.exports = {

48

plugins: [

49

new BundleAnalyzerPlugin()

50

]

51

};

52

```

53

54

### As CLI Tool

55

56

```bash

57

# Generate webpack stats file first

58

webpack --profile --json > stats.json

59

60

# Analyze the bundle

61

webpack-bundle-analyzer stats.json

62

```

63

64

## Architecture

65

66

Webpack Bundle Analyzer consists of several core components:

67

68

- **BundleAnalyzerPlugin**: Main webpack plugin for integration into build process

69

- **CLI Tool**: Standalone command-line interface for analyzing existing stats files

70

- **Viewer**: Web-based visualization engine with interactive treemap

71

- **Analyzer**: Core parsing and data processing engine for webpack stats

72

- **Report Generator**: Static HTML and JSON report generation capabilities

73

74

## Capabilities

75

76

### Webpack Plugin Integration

77

78

Primary plugin class for webpack integration, providing configurable bundle analysis during builds with multiple output modes and visualization options.

79

80

```javascript { .api }

81

class BundleAnalyzerPlugin {

82

constructor(options?: BundleAnalyzerOptions);

83

apply(compiler: object): void;

84

}

85

86

interface BundleAnalyzerOptions {

87

analyzerMode?: 'server' | 'static' | 'json' | 'disabled';

88

analyzerHost?: string;

89

analyzerPort?: number | 'auto';

90

analyzerUrl?: (options: { listenHost: string; listenPort: number; boundAddress: object }) => string;

91

reportFilename?: string;

92

reportTitle?: string | (() => string);

93

defaultSizes?: 'stat' | 'parsed' | 'gzip';

94

openAnalyzer?: boolean;

95

generateStatsFile?: boolean;

96

statsFilename?: string;

97

statsOptions?: object;

98

excludeAssets?: string | RegExp | ((assetName: string) => boolean) | Array<string | RegExp | ((assetName: string) => boolean)>;

99

logLevel?: 'info' | 'warn' | 'error' | 'silent';

100

}

101

```

102

103

[Webpack Plugin](./webpack-plugin.md)

104

105

### CLI Tool

106

107

Command-line interface for analyzing webpack bundle stats files with flexible output modes and server capabilities.

108

109

```javascript { .api }

110

// CLI Command Format

111

webpack-bundle-analyzer <bundleStatsFile> [bundleDir] [options]

112

113

// Available CLI Options

114

interface CLIOptions {

115

mode?: 'server' | 'static' | 'json';

116

host?: string;

117

port?: number | 'auto';

118

report?: string;

119

title?: string;

120

defaultSizes?: 'stat' | 'parsed' | 'gzip';

121

open?: boolean;

122

exclude?: string[];

123

logLevel?: 'debug' | 'info' | 'warn' | 'error' | 'silent';

124

}

125

```

126

127

[CLI Tool](./cli-tool.md)

128

129

### Server Function (Legacy)

130

131

Legacy function for starting development server with bundle visualization. This is an alias for the `startServer` function from the viewer module.

132

133

```javascript { .api }

134

/**

135

* Start HTTP server with interactive bundle visualization (deprecated alias)

136

* @param bundleStats - Webpack stats object

137

* @param options - Server configuration options

138

* @returns Promise resolving to server instance

139

*/

140

function start(

141

bundleStats: object,

142

options?: ServerOptions

143

): Promise<ServerInstance>;

144

```

145

146

Note: This function is deprecated. Use the Report Generation capabilities or viewer module directly for new code.

147

148

### Bundle Analysis & Visualization

149

150

Core analysis engine that processes webpack stats and generates interactive visualizations with multiple size metrics and filtering capabilities.

151

152

```javascript { .api }

153

function getViewerData(

154

bundleStats: object,

155

bundleDir: string,

156

options?: AnalyzerOptions

157

): BundleInfo[];

158

159

interface AnalyzerOptions {

160

logger?: Logger;

161

excludeAssets?: string | RegExp | ((assetName: string) => boolean) | Array<string | RegExp | ((assetName: string) => boolean)>;

162

}

163

164

interface BundleInfo {

165

label: string;

166

isAsset: boolean;

167

statSize: number;

168

parsedSize?: number;

169

gzipSize?: number;

170

groups: ChartData[];

171

isInitialByEntrypoint: { [entrypoint: string]: boolean };

172

}

173

```

174

175

[Analysis Engine](./analysis-engine.md)

176

177

### Report Generation

178

179

Static report generation system for creating HTML and JSON reports with customizable output options and browser integration.

180

181

```javascript { .api }

182

function generateReport(

183

bundleStats: object,

184

options?: ReportOptions

185

): Promise<void>;

186

187

function generateJSONReport(

188

bundleStats: object,

189

options?: JSONReportOptions

190

): Promise<void>;

191

192

interface ReportOptions {

193

openBrowser?: boolean;

194

reportFilename: string;

195

reportTitle?: string | (() => string);

196

bundleDir?: string;

197

logger?: Logger;

198

defaultSizes?: 'stat' | 'parsed' | 'gzip';

199

excludeAssets?: string | RegExp | ((assetName: string) => boolean) | Array<string | RegExp | ((assetName: string) => boolean)>;

200

}

201

202

interface JSONReportOptions {

203

reportFilename: string;

204

bundleDir?: string;

205

logger?: Logger;

206

excludeAssets?: string | RegExp | ((assetName: string) => boolean) | Array<string | RegExp | ((assetName: string) => boolean)>;

207

}

208

```

209

210

[Report Generation](./report-generation.md)

211

212

### Utilities

213

214

Core utility functions for advanced usage scenarios and custom integrations.

215

216

```javascript { .api }

217

/**

218

* Creates asset filter function from exclude patterns

219

* @param excludePatterns - Pattern or array of patterns to exclude assets

220

* @returns Filter function that returns true for included assets

221

*/

222

function createAssetsFilter(

223

excludePatterns: string | RegExp | ((assetName: string) => boolean) | Array<string | RegExp | ((assetName: string) => boolean)>

224

): (assetName: string) => boolean;

225

226

/**

227

* Default title generation function

228

* @returns Formatted title with current date and time

229

*/

230

function defaultTitle(): string;

231

232

/**

233

* Default analyzer URL generation function

234

* @param options - Server address options

235

* @returns Complete URL for server mode

236

*/

237

function defaultAnalyzerUrl(options: { listenHost: string; boundAddress: { port: number } }): string;

238

239

/**

240

* Opens URL in default browser with error handling

241

* @param uri - URL to open

242

* @param logger - Logger for error messages

243

*/

244

function open(uri: string, logger: Logger): void;

245

246

/**

247

* Parse webpack bundle file to extract module information

248

* @param bundlePath - Path to bundle file

249

* @returns Bundle parsing result with modules and runtime info

250

*/

251

function parseBundle(bundlePath: string): {

252

src: string;

253

runtimeSrc: string;

254

modules: { [moduleId: string]: string };

255

};

256

257

/**

258

* Write webpack stats to file with streaming

259

* @param stats - Webpack stats object

260

* @param filepath - Output file path

261

* @returns Promise that completes when file is written

262

*/

263

function writeStats(stats: object, filepath: string): Promise<void>;

264

```

265

266

### Logger

267

268

Configurable logging system with multiple log levels and console output.

269

270

```javascript { .api }

271

class Logger {

272

static levels: string[];

273

static defaultLevel: string;

274

275

constructor(level?: string);

276

setLogLevel(level: string): void;

277

debug(...args: any[]): void;

278

info(...args: any[]): void;

279

warn(...args: any[]): void;

280

error(...args: any[]): void;

281

}

282

```

283

284

## Types

285

286

### Core Types

287

288

```javascript { .api }

289

// Size Types

290

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

291

292

// Analyzer Modes

293

type AnalyzerMode = 'server' | 'static' | 'json' | 'disabled';

294

295

// Log Levels

296

type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'silent';

297

298

// Asset Filter Pattern

299

type AssetFilterPattern =

300

| string

301

| RegExp

302

| ((assetName: string) => boolean);

303

304

// Chart Data Structure

305

interface ChartData {

306

label: string;

307

value: number;

308

children?: ChartData[];

309

}

310

311

// Logger Interface

312

interface Logger {

313

/** Available log levels */

314

static levels: string[];

315

/** Default log level */

316

static defaultLevel: string;

317

318

/** Current active log levels */

319

activeLevels: Set<string>;

320

321

/** Set the logging level */

322

setLogLevel(level: LogLevel): void;

323

324

/** Log debug messages */

325

debug(...args: any[]): void;

326

/** Log informational messages */

327

info(...args: any[]): void;

328

/** Log warning messages */

329

warn(...args: any[]): void;

330

/** Log error messages */

331

error(...args: any[]): void;

332

}

333

334

// Bundle Parsing Result

335

interface BundleParseResult {

336

/** Complete bundle source code */

337

src: string;

338

/** Runtime/entry source code */

339

runtimeSrc: string;

340

/** Map of module IDs to their source code */

341

modules: { [moduleId: string]: string };

342

}

343

```