viewer.js
6.19 KB
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
190
191
192
193
194
195
196
197
'use strict';
var startServer = function () {
var _ref = _asyncToGenerator(function* (bundleStats, opts) {
var _ref2 = opts || {},
_ref2$port = _ref2.port,
port = _ref2$port === undefined ? 8888 : _ref2$port,
_ref2$host = _ref2.host,
host = _ref2$host === undefined ? '127.0.0.1' : _ref2$host,
_ref2$openBrowser = _ref2.openBrowser,
openBrowser = _ref2$openBrowser === undefined ? true : _ref2$openBrowser,
_ref2$bundleDir = _ref2.bundleDir,
bundleDir = _ref2$bundleDir === undefined ? null : _ref2$bundleDir,
_ref2$logger = _ref2.logger,
logger = _ref2$logger === undefined ? new Logger() : _ref2$logger,
_ref2$defaultSizes = _ref2.defaultSizes,
defaultSizes = _ref2$defaultSizes === undefined ? 'parsed' : _ref2$defaultSizes,
_ref2$excludeAssets = _ref2.excludeAssets,
excludeAssets = _ref2$excludeAssets === undefined ? null : _ref2$excludeAssets;
var analyzerOpts = { logger, excludeAssets };
var chartData = getChartData(analyzerOpts, bundleStats, bundleDir);
if (!chartData) return;
var app = express();
// Explicitly using our `ejs` dependency to render templates
// Fixes #17
app.engine('ejs', require('ejs').renderFile);
app.set('view engine', 'ejs');
app.set('views', `${projectRoot}/views`);
app.use(express.static(`${projectRoot}/public`));
app.use('/', function (req, res) {
res.render('viewer', {
mode: 'server',
get chartData() {
return JSON.stringify(chartData);
},
defaultSizes: JSON.stringify(defaultSizes)
});
});
var server = http.createServer(app);
yield new Promise(function (resolve) {
server.listen(port, host, function () {
resolve();
var 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) {
opener(url);
}
});
});
var wss = new WebSocket.Server({ server });
wss.on('connection', function (ws) {
ws.on('error', function (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) {
var newChartData = getChartData(analyzerOpts, bundleStats, bundleDir);
if (!newChartData) return;
chartData = newChartData;
wss.clients.forEach(function (client) {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({
event: 'chartDataUpdated',
data: newChartData
}));
}
});
}
});
return function startServer(_x, _x2) {
return _ref.apply(this, arguments);
};
}();
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
var path = require('path');
var fs = require('fs');
var http = require('http');
var WebSocket = require('ws');
var _ = require('lodash');
var express = require('express');
var ejs = require('ejs');
var opener = require('opener');
var mkdir = require('mkdirp');
var _require = require('chalk'),
bold = _require.bold;
var Logger = require('./Logger');
var analyzer = require('./analyzer');
var projectRoot = path.resolve(__dirname, '..');
module.exports = {
startServer,
generateReport,
// deprecated
start: startServer
};
function generateReport(bundleStats, opts) {
var _ref3 = opts || {},
_ref3$openBrowser = _ref3.openBrowser,
openBrowser = _ref3$openBrowser === undefined ? true : _ref3$openBrowser,
_ref3$reportFilename = _ref3.reportFilename,
reportFilename = _ref3$reportFilename === undefined ? 'report.html' : _ref3$reportFilename,
_ref3$bundleDir = _ref3.bundleDir,
bundleDir = _ref3$bundleDir === undefined ? null : _ref3$bundleDir,
_ref3$logger = _ref3.logger,
logger = _ref3$logger === undefined ? new Logger() : _ref3$logger,
_ref3$defaultSizes = _ref3.defaultSizes,
defaultSizes = _ref3$defaultSizes === undefined ? 'parsed' : _ref3$defaultSizes,
_ref3$excludeAssets = _ref3.excludeAssets,
excludeAssets = _ref3$excludeAssets === undefined ? null : _ref3$excludeAssets;
var chartData = getChartData({ logger, excludeAssets }, bundleStats, bundleDir);
if (!chartData) return;
ejs.renderFile(`${projectRoot}/views/viewer.ejs`, {
mode: 'static',
chartData: JSON.stringify(chartData),
assetContent: getAssetContent,
defaultSizes: JSON.stringify(defaultSizes)
}, function (err, reportHtml) {
if (err) return logger.error(err);
var reportFilepath = path.resolve(bundleDir || process.cwd(), reportFilename);
mkdir.sync(path.dirname(reportFilepath));
fs.writeFileSync(reportFilepath, reportHtml);
logger.info(`${bold('Webpack Bundle Analyzer')} saved report to ${bold(reportFilepath)}`);
if (openBrowser) {
opener(`file://${reportFilepath}`);
}
});
}
function getAssetContent(filename) {
return fs.readFileSync(`${projectRoot}/public/${filename}`, 'utf8');
}
function getChartData(analyzerOpts) {
var chartData = void 0;
var logger = analyzerOpts.logger;
try {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
chartData = analyzer.getViewerData.apply(analyzer, args.concat([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;
}