0
# Report Generation
1
2
The report generation system creates static HTML and JSON reports from webpack bundle analysis data. It provides flexible output formats, customizable templates, and browser integration for sharing and archiving bundle analysis results.
3
4
## Capabilities
5
6
### Static HTML Report Generation
7
8
Generate standalone HTML files with embedded bundle visualization and interactive features.
9
10
```javascript { .api }
11
/**
12
* Generates static HTML report with embedded bundle visualization
13
* @param bundleStats - Webpack stats object
14
* @param options - Report generation options
15
*/
16
function generateReport(
17
bundleStats: object,
18
options?: ReportOptions
19
): Promise<void>;
20
21
interface ReportOptions {
22
/** Whether to automatically open report in browser */
23
openBrowser?: boolean;
24
/** Output file path for HTML report */
25
reportFilename: string;
26
/** Report title (string or function returning string) */
27
reportTitle?: string | (() => string);
28
/** Directory containing bundle files for size analysis */
29
bundleDir?: string;
30
/** Logger instance for output messages */
31
logger?: Logger;
32
/** Default size type to display in visualization */
33
defaultSizes?: 'stat' | 'parsed' | 'gzip';
34
/** Patterns to exclude assets from report */
35
excludeAssets?: string | RegExp | ((assetName: string) => boolean) | Array<string | RegExp | ((assetName: string) => boolean)>;
36
}
37
```
38
39
**Usage Examples:**
40
41
```javascript
42
const { generateReport } = require('webpack-bundle-analyzer/lib/viewer');
43
const fs = require('fs');
44
45
// Load webpack stats
46
const stats = JSON.parse(fs.readFileSync('stats.json'));
47
48
// Basic HTML report
49
await generateReport(stats, {
50
reportFilename: 'bundle-report.html'
51
});
52
53
// Customized report
54
await generateReport(stats, {
55
reportFilename: './reports/production-bundle.html',
56
reportTitle: 'Production Bundle Analysis',
57
bundleDir: './dist',
58
defaultSizes: 'gzip',
59
openBrowser: false,
60
excludeAssets: /\.css$/
61
});
62
63
// Dynamic title with timestamp
64
await generateReport(stats, {
65
reportFilename: 'bundle-report.html',
66
reportTitle: () => `Bundle Report - ${new Date().toISOString()}`
67
});
68
```
69
70
### JSON Report Generation
71
72
Generate JSON files containing structured bundle analysis data for programmatic consumption.
73
74
```javascript { .api }
75
/**
76
* Generates JSON report with bundle analysis data
77
* @param bundleStats - Webpack stats object
78
* @param options - JSON report options
79
*/
80
function generateJSONReport(
81
bundleStats: object,
82
options?: JSONReportOptions
83
): Promise<void>;
84
85
interface JSONReportOptions {
86
/** Output file path for JSON report */
87
reportFilename: string;
88
/** Directory containing bundle files for size analysis */
89
bundleDir?: string;
90
/** Logger instance for output messages */
91
logger?: Logger;
92
/** Patterns to exclude assets from report */
93
excludeAssets?: string | RegExp | ((assetName: string) => boolean) | Array<string | RegExp | ((assetName: string) => boolean)>;
94
}
95
```
96
97
**Usage Examples:**
98
99
```javascript
100
const { generateJSONReport } = require('webpack-bundle-analyzer/lib/viewer');
101
102
// Basic JSON report
103
await generateJSONReport(stats, {
104
reportFilename: 'bundle-data.json'
105
});
106
107
// Customized JSON report
108
await generateJSONReport(stats, {
109
reportFilename: './data/bundle-analysis.json',
110
bundleDir: './dist',
111
excludeAssets: ['vendor', /\.css$/]
112
});
113
```
114
115
### Development Server
116
117
Start a development server with live bundle visualization and WebSocket updates.
118
119
```javascript { .api }
120
/**
121
* Starts HTTP server with interactive bundle visualization
122
* @param bundleStats - Webpack stats object
123
* @param options - Server configuration options
124
* @returns Server instance with update capabilities
125
*/
126
function startServer(
127
bundleStats: object,
128
options?: ServerOptions
129
): Promise<ServerInstance>;
130
131
interface ServerOptions {
132
/** Server port number or 'auto' for automatic assignment */
133
port?: number | 'auto';
134
/** Server host address */
135
host?: string;
136
/** Whether to automatically open browser */
137
openBrowser?: boolean;
138
/** Directory containing bundle files */
139
bundleDir?: string;
140
/** Logger instance */
141
logger?: Logger;
142
/** Default size type to display */
143
defaultSizes?: 'stat' | 'parsed' | 'gzip';
144
/** Asset exclusion patterns */
145
excludeAssets?: string | RegExp | ((assetName: string) => boolean) | Array<string | RegExp | ((assetName: string) => boolean)>;
146
/** Report title */
147
reportTitle?: string | (() => string);
148
/** Custom URL generation function */
149
analyzerUrl?: (options: { listenHost: string; listenPort: number; boundAddress: object }) => string;
150
}
151
152
interface ServerInstance {
153
/** WebSocket server for live updates */
154
ws: object;
155
/** HTTP server instance */
156
http: object;
157
/** Update chart data and notify connected clients */
158
updateChartData: (bundleStats: object) => void;
159
}
160
```
161
162
**Usage Examples:**
163
164
```javascript
165
const { startServer } = require('webpack-bundle-analyzer/lib/viewer');
166
167
// Basic server
168
const server = await startServer(stats);
169
170
// Custom server configuration
171
const server = await startServer(stats, {
172
port: 9999,
173
host: '0.0.0.0',
174
openBrowser: false,
175
bundleDir: './dist',
176
defaultSizes: 'gzip'
177
});
178
179
// Update data (useful for webpack watch mode)
180
const newStats = getUpdatedStats();
181
server.updateChartData(newStats);
182
```
183
184
### Report Template System
185
186
Customizable HTML template system for generating static reports with embedded assets.
187
188
```javascript { .api }
189
/**
190
* Renders HTML report using template system
191
* @param options - Template rendering options
192
* @returns Complete HTML string
193
*/
194
function renderViewer(options: TemplateOptions): string;
195
196
interface TemplateOptions {
197
/** Report title for HTML title tag */
198
title?: string;
199
/** Enable WebSocket connection for live updates */
200
enableWebSocket?: boolean;
201
/** Bundle analysis data for visualization */
202
chartData: object;
203
/** Webpack entrypoint information */
204
entrypoints: string[];
205
/** Default size type to display */
206
defaultSizes?: 'stat' | 'parsed' | 'gzip';
207
/** Template mode: 'server' for dynamic assets, 'static' for embedded */
208
mode: 'server' | 'static';
209
}
210
```
211
212
### Entrypoint Information
213
214
Extract webpack entrypoint information for enhanced bundle analysis context.
215
216
```javascript { .api }
217
/**
218
* Extracts entrypoint names from webpack stats
219
* @param bundleStats - Webpack stats object
220
* @returns Array of entrypoint names
221
*/
222
function getEntrypoints(bundleStats: object): string[];
223
```
224
225
**Usage Examples:**
226
227
```javascript
228
const { getEntrypoints } = require('webpack-bundle-analyzer/lib/viewer');
229
230
const entrypoints = getEntrypoints(stats);
231
console.log('Available entrypoints:', entrypoints);
232
// Output: ['main', 'vendor', 'runtime']
233
```
234
235
### Browser Integration
236
237
Automatic browser opening with cross-platform support and error handling.
238
239
```javascript { .api }
240
/**
241
* Opens URL in default browser with error handling
242
* @param uri - URL to open
243
* @param logger - Logger for error messages
244
*/
245
function open(uri: string, logger: Logger): void;
246
```
247
248
**Features:**
249
250
- Cross-platform browser detection
251
- Fallback handling for headless environments
252
- Silent error handling for CI/CD scenarios
253
- Support for custom URL schemes
254
255
### File Output Management
256
257
Robust file output system with directory creation and error handling.
258
259
**Features:**
260
261
- Automatic directory creation for nested paths
262
- Atomic file writing to prevent corruption
263
- Path validation and security checks
264
- Proper error handling and logging
265
266
**Usage Examples:**
267
268
```javascript
269
// Reports with nested directory structure
270
await generateReport(stats, {
271
reportFilename: './reports/production/bundle-analysis.html'
272
});
273
274
await generateJSONReport(stats, {
275
reportFilename: './data/analysis/bundle-data.json'
276
});
277
```
278
279
### Report Customization
280
281
Extensive customization options for tailoring reports to specific needs.
282
283
**Title Customization:**
284
285
```javascript
286
// Static title
287
reportTitle: 'Production Bundle Analysis'
288
289
// Dynamic title with build info
290
reportTitle: () => `Bundle Analysis - Build ${process.env.BUILD_NUMBER}`
291
292
// Date-based title
293
reportTitle: () => `Bundle Report - ${new Date().toLocaleDateString()}`
294
```
295
296
**Size Display Options:**
297
298
```javascript
299
// Show original source sizes
300
defaultSizes: 'stat'
301
302
// Show minified bundle sizes (default)
303
defaultSizes: 'parsed'
304
305
// Show compressed transfer sizes
306
defaultSizes: 'gzip'
307
```
308
309
**Asset Filtering:**
310
311
```javascript
312
// Exclude development assets
313
excludeAssets: /\.(map|test\.js)$/
314
315
// Exclude by name pattern
316
excludeAssets: 'hot-update'
317
318
// Complex filtering logic
319
excludeAssets: (assetName) => {
320
return assetName.includes('dev') ||
321
assetName.includes('test') ||
322
assetName.endsWith('.map');
323
}
324
```