analyzer.js
2.52 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
#! /usr/bin/env node
const { resolve, dirname } = require('path');
const _ = require('lodash');
const commander = require('commander');
const { magenta } = require('chalk');
const analyzer = require('../analyzer');
const viewer = require('../viewer');
const program = commander
.version(require('../../package.json').version)
.usage(
`<bundleStatsFile> [bundleDir] [options]
Arguments:
bundleStatsFile Path to Webpack Stats JSON file.
bundleDir Directory containing all generated bundles.
You should provided it if you want analyzer to show you the real parsed module sizes.
By default a directory of stats file is used.`
)
.option(
'-m, --mode <mode>',
'Analyzer mode. Should be `server` or `static`.' +
br('In `server` mode analyzer will start HTTP server to show bundle report.') +
br('In `static` mode single HTML file with bundle report will be generated.') +
br('Default is `server`.'),
'server'
)
.option(
'-p, --port <n>',
'Port that will be used in `server` mode to start HTTP server.' +
br('Default is 8888.'),
Number,
8888
)
.option(
'-r, --report <file>',
'Path to bundle report file that will be generated in `static` mode.' +
br('Default is `report.html`.'),
'report.html'
)
.option(
'-O, --no-open',
"Don't open report in default browser automatically."
)
.parse(process.argv);
let {
mode,
port,
report: reportFilename,
open: openBrowser,
args: [bundleStatsFile, bundleDir]
} = program;
if (!bundleStatsFile) showHelp('Provide path to Webpack Stats file as first argument');
if (mode !== 'server' && mode !== 'static') showHelp('Invalid mode. Should be either `server` or `static`.');
if (mode === 'server' && isNaN(port)) showHelp('Invalid port number');
bundleStatsFile = resolve(bundleStatsFile);
if (!bundleDir) bundleDir = dirname(bundleStatsFile);
let bundleStats;
try {
bundleStats = analyzer.readStatsFromFile(bundleStatsFile);
} catch (err) {
console.error(`Could't read webpack bundle stats from "${bundleStatsFile}":\n${err}`);
process.exit(1);
}
if (mode === 'server') {
viewer.startServer(bundleStats, {
openBrowser,
port,
bundleDir
});
} else {
viewer.generateReport(bundleStats, {
openBrowser,
reportFilename: resolve(reportFilename),
bundleDir
});
}
function showHelp(error) {
if (error) console.log(`\n ${magenta(error)}`);
program.outputHelp();
process.exit(1);
}
function br(str) {
return `\n${_.repeat(' ', 21)}${str}`;
}