-
-
Notifications
You must be signed in to change notification settings - Fork 493
/
Copy pathviewer.js
189 lines (150 loc) · 4.47 KB
/
viewer.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
const path = require('path');
const http = require('http');
const WebSocket = require('ws');
const sirv = require('sirv');
const _ = require('lodash');
const {bold} = require('chalk');
const Logger = require('./Logger');
const analyzer = require('./analyzer');
const {open, mkdirpSync} = require('./utils');
const {renderViewer} = require('./template');
const projectRoot = path.resolve(__dirname, '..');
function resolveTitle(reportTitle) {
if (typeof reportTitle === 'function') {
return reportTitle();
} else {
return reportTitle;
}
}
module.exports = {
startServer,
generateReport,
generateJSONReport,
// deprecated
start: startServer
};
async function startServer(bundleStats, opts) {
const {
port = 8888,
host = '127.0.0.1',
openBrowser = true,
bundleDir = null,
logger = new Logger(),
defaultSizes = 'parsed',
excludeAssets = null,
reportTitle
} = opts || {};
const analyzerOpts = {logger, excludeAssets};
let chartData = getChartData(analyzerOpts, bundleStats, bundleDir);
if (!chartData) return;
const sirvMiddleware = sirv(`${projectRoot}/public`, {
// disables caching and traverse the file system on every request
dev: true
});
const server = http.createServer((req, res) => {
if (req.method === 'GET' && req.url === '/') {
const html = renderViewer({
mode: 'server',
title: resolveTitle(reportTitle),
chartData,
defaultSizes,
enableWebSocket: true
});
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(html);
} else {
sirvMiddleware(req, res);
}
});
await new Promise(resolve => {
server.listen(port, host, () => {
resolve();
const url = `http://${host}:${server.address().port}`;
logger.info(
`${bold('Webpack Bundle Analyzer')} is started at ${bold(url)}\n` +
`Use ${bold('Ctrl+C')} to close it`
);
if (openBrowser) {
open(url, logger);
}
});
});
const wss = new WebSocket.Server({server});
wss.on('connection', ws => {
ws.on('error', err => {
// Ignore network errors like `ECONNRESET`, `EPIPE`, etc.
if (err.errno) return;
logger.info(err.message);
});
});
return {
ws: wss,
http: server,
updateChartData
};
function updateChartData(bundleStats) {
const newChartData = getChartData(analyzerOpts, bundleStats, bundleDir);
if (!newChartData) return;
chartData = newChartData;
wss.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({
event: 'chartDataUpdated',
data: newChartData
}));
}
});
}
}
async function generateReport(bundleStats, opts) {
const {
openBrowser = true,
reportFilename,
reportTitle,
bundleDir = null,
logger = new Logger(),
defaultSizes = 'parsed',
excludeAssets = null,
fs
} = opts || {};
const chartData = getChartData({logger, excludeAssets}, bundleStats, bundleDir);
if (!chartData) return;
const reportHtml = renderViewer({
mode: 'static',
title: resolveTitle(reportTitle),
chartData,
defaultSizes,
enableWebSocket: false
});
const reportFilepath = path.resolve(bundleDir || process.cwd(), reportFilename);
mkdirpSync(fs, reportFilepath, reportHtml);
fs.writeFileSync(reportFilepath, reportHtml);
logger.info(`${bold('Webpack Bundle Analyzer')} saved report to ${bold(reportFilepath)}`);
if (openBrowser) {
open(`file://${reportFilepath}`, logger);
}
}
async function generateJSONReport(bundleStats, opts) {
const {reportFilename, bundleDir = null, logger = new Logger(), excludeAssets = null, fs} = opts || {};
const chartData = getChartData({logger, excludeAssets}, bundleStats, bundleDir);
if (!chartData) return;
mkdirpSync(fs, reportFilename);
fs.writeFileSync(reportFilename, JSON.stringify(chartData));
logger.info(`${bold('Webpack Bundle Analyzer')} saved JSON report to ${bold(reportFilename)}`);
}
function getChartData(analyzerOpts, ...args) {
let chartData;
const {logger} = analyzerOpts;
try {
chartData = analyzer.getViewerData(...args, analyzerOpts);
} catch (err) {
logger.error(`Could't analyze webpack bundle:\n${err}`);
logger.debug(err.stack);
chartData = null;
}
if (_.isPlainObject(chartData) && _.isEmpty(chartData)) {
logger.error("Could't find any javascript bundles in provided stats file");
chartData = null;
}
return chartData;
}