UNPKG

2.9 kBJavaScriptView Raw
1'use strict';
2
3var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
4
5function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
6
7var viewer = require('./viewer');
8
9var BundleAnalyzerPlugin = function () {
10 function BundleAnalyzerPlugin(opts) {
11 _classCallCheck(this, BundleAnalyzerPlugin);
12
13 this.opts = _extends({
14 analyzerMode: 'server',
15 analyzerPort: 8888,
16 reportFilename: 'report.html',
17 openAnalyzer: true,
18 generateStatsFile: false,
19 statsFilename: 'stats.json',
20 // deprecated
21 startAnalyzer: true
22 }, opts);
23 }
24
25 BundleAnalyzerPlugin.prototype.apply = function apply(compiler) {
26 var _this = this;
27
28 this.compiler = compiler;
29
30 compiler.plugin('emit', function (curCompiler, callback) {
31 var stats = curCompiler.getStats().toJson();
32
33 if (_this.opts.generateStatsFile) {
34 (function () {
35 var statsStr = JSON.stringify(stats, null, 2);
36
37 curCompiler.assets[_this.opts.statsFilename] = {
38 source: function source() {
39 return statsStr;
40 },
41 size: function size() {
42 return statsStr.length;
43 }
44 };
45 })();
46 }
47
48 var analyzeFn = void 0;
49
50 // Handling deprecated `startAnalyzer` flag
51 if (_this.opts.analyzerMode === 'server' && !_this.opts.startAnalyzer) {
52 _this.opts.analyzerMode = 'disabled';
53 }
54
55 if (_this.opts.analyzerMode === 'server') {
56 analyzeFn = function analyzeFn() {
57 return _this.startAnalyzerServer(stats);
58 };
59 } else if (_this.opts.analyzerMode === 'static') {
60 analyzeFn = function analyzeFn() {
61 return _this.generateStaticReport(stats);
62 };
63 }
64
65 if (analyzeFn) {
66 // Making analyzer logs to be after all webpack warnings in the console
67 setTimeout(function () {
68 console.log('');
69 analyzeFn();
70 }, 500);
71 }
72
73 callback();
74 });
75 };
76
77 BundleAnalyzerPlugin.prototype.startAnalyzerServer = function startAnalyzerServer(stats) {
78 viewer.startServer(stats, {
79 openBrowser: this.opts.openAnalyzer,
80 port: this.opts.analyzerPort,
81 bundleDir: this.compiler.outputPath
82 });
83 };
84
85 BundleAnalyzerPlugin.prototype.generateStaticReport = function generateStaticReport(stats) {
86 viewer.generateReport(stats, {
87 openBrowser: this.opts.openAnalyzer,
88 reportFilename: this.opts.reportFilename,
89 bundleDir: this.compiler.outputPath
90 });
91 };
92
93 return BundleAnalyzerPlugin;
94}();
95
96module.exports = BundleAnalyzerPlugin;
\No newline at end of file