-
-
Notifications
You must be signed in to change notification settings - Fork 503
Expand file tree
/
Copy pathBundleAnalyzerPlugin.js
More file actions
258 lines (233 loc) · 8.36 KB
/
BundleAnalyzerPlugin.js
File metadata and controls
258 lines (233 loc) · 8.36 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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
const fs = require("node:fs");
const path = require("node:path");
const { bold } = require("picocolors");
const Logger = require("./Logger");
const { writeStats } = require("./statsUtils");
const utils = require("./utils");
const viewer = require("./viewer");
/** @typedef {import("net").AddressInfo} AddressInfo */
/** @typedef {import("webpack").Compiler} Compiler */
/** @typedef {import("webpack").OutputFileSystem} OutputFileSystem */
/** @typedef {import("webpack").Stats} Stats */
/** @typedef {import("webpack").StatsOptions} StatsOptions */
/** @typedef {import("webpack").StatsAsset} StatsAsset */
/** @typedef {import("webpack").StatsCompilation} StatsCompilation */
/** @typedef {import("./sizeUtils").Algorithm} CompressionAlgorithm */
/** @typedef {import("./Logger").Level} LogLever */
/** @typedef {import("./viewer").ViewerServerObj} ViewerServerObj */
/** @typedef {string | boolean | StatsOptions} PluginStatsOptions */
// eslint-disable-next-line jsdoc/reject-any-type
/** @typedef {any} EXPECTED_ANY */
/** @typedef {"static" | "json" | "server" | "disabled"} Mode */
/** @typedef {string | RegExp | ((asset: string) => void)} Pattern */
/** @typedef {null | Pattern | Pattern[]} ExcludeAssets */
/** @typedef {"stat" | "parsed" | "gzip" | "brotli" | "zstd"} Sizes */
/** @typedef {string | (() => string)} ReportTitle */
/** @typedef {(options: { listenHost: string, listenPort: number, boundAddress: string | AddressInfo | null }) => string} AnalyzerUrl */
/**
* @typedef {object} Options
* @property {Mode=} analyzerMode analyzer mode
* @property {string=} analyzerHost analyzer host
* @property {"auto" | number=} analyzerPort analyzer port
* @property {CompressionAlgorithm=} compressionAlgorithm compression algorithm
* @property {string | null=} reportFilename report filename
* @property {ReportTitle=} reportTitle report title
* @property {Sizes=} defaultSizes default sizes
* @property {boolean=} openAnalyzer open analyzer
* @property {boolean=} generateStatsFile generate stats file
* @property {string=} statsFilename stats filename
* @property {PluginStatsOptions=} statsOptions stats options
* @property {ExcludeAssets=} excludeAssets exclude assets
* @property {LogLever=} logLevel exclude assets
* @property {boolean=} startAnalyzer start analyzer
* @property {AnalyzerUrl=} analyzerUrl start analyzer
*/
class BundleAnalyzerPlugin {
/**
* @param {Options=} opts options
*/
constructor(opts = {}) {
/** @type {Required<Omit<Options, "analyzerPort" | "statsOptions">> & { analyzerPort: number, statsOptions: undefined | PluginStatsOptions }} */
this.opts = {
analyzerMode: "server",
analyzerHost: "127.0.0.1",
compressionAlgorithm: "gzip",
reportFilename: null,
reportTitle: utils.defaultTitle,
defaultSizes: "parsed",
openAnalyzer: true,
generateStatsFile: false,
statsFilename: "stats.json",
statsOptions: undefined,
excludeAssets: null,
logLevel: "info",
// TODO deprecated
startAnalyzer: true,
analyzerUrl: utils.defaultAnalyzerUrl,
...opts,
analyzerPort:
opts.analyzerPort === "auto" ? 0 : (opts.analyzerPort ?? 8888),
};
/** @type {Compiler | null} */
this.compiler = null;
/** @type {Promise<ViewerServerObj> | null} */
this.server = null;
this.logger = new Logger(this.opts.logLevel);
}
/**
* @param {Compiler} compiler compiler
*/
apply(compiler) {
this.compiler = compiler;
/**
* @param {Stats} stats stats
* @param {(err?: Error) => void} callback callback
*/
const done = (stats, callback) => {
callback ||= () => {};
/** @type {(() => Promise<void>)[]} */
const actions = [];
if (this.opts.generateStatsFile) {
actions.push(() =>
this.generateStatsFile(stats.toJson(this.opts.statsOptions)),
);
}
// Handling deprecated `startAnalyzer` flag
if (this.opts.analyzerMode === "server" && !this.opts.startAnalyzer) {
this.opts.analyzerMode = "disabled";
}
if (this.opts.analyzerMode === "server") {
actions.push(() => this.startAnalyzerServer(stats.toJson()));
} else if (this.opts.analyzerMode === "static") {
actions.push(() => this.generateStaticReport(stats.toJson()));
} else if (this.opts.analyzerMode === "json") {
actions.push(() => this.generateJSONReport(stats.toJson()));
}
if (actions.length) {
// Making analyzer logs to be after all webpack logs in the console
setImmediate(async () => {
try {
await Promise.all(actions.map((action) => action()));
callback();
} catch (err) {
callback(/** @type {Error} */ (err));
}
});
} else {
callback();
}
};
if (compiler.hooks) {
compiler.hooks.done.tapAsync("webpack-bundle-analyzer", done);
} else {
// @ts-expect-error old webpack@4 API
compiler.plugin("done", done);
}
}
/**
* @param {StatsCompilation} stats stats
* @returns {Promise<void>}
*/
async generateStatsFile(stats) {
const statsFilepath = path.resolve(
/** @type {Compiler} */
(this.compiler).outputPath,
this.opts.statsFilename,
);
await fs.promises.mkdir(path.dirname(statsFilepath), { recursive: true });
try {
await writeStats(stats, statsFilepath);
this.logger.info(
`${bold("Webpack Bundle Analyzer")} saved stats file to ${bold(statsFilepath)}`,
);
} catch (error) {
this.logger.error(
`${bold("Webpack Bundle Analyzer")} error saving stats file to ${bold(statsFilepath)}: ${error}`,
);
}
}
/**
* @param {StatsCompilation} stats stats
* @returns {Promise<void>}
*/
async startAnalyzerServer(stats) {
if (this.server) {
(await this.server).updateChartData(stats);
} else {
this.server = viewer.startServer(stats, {
openBrowser: this.opts.openAnalyzer,
host: this.opts.analyzerHost,
port: this.opts.analyzerPort,
reportTitle: this.opts.reportTitle,
compressionAlgorithm: this.opts.compressionAlgorithm,
bundleDir: this.getBundleDirFromCompiler(),
outputFs: this.getOutputFsFromCompiler(),
logger: this.logger,
defaultSizes: this.opts.defaultSizes,
excludeAssets: this.opts.excludeAssets,
analyzerUrl: this.opts.analyzerUrl,
});
}
}
/**
* @param {StatsCompilation} stats stats
* @returns {Promise<void>}
*/
async generateJSONReport(stats) {
await viewer.generateJSONReport(stats, {
reportFilename: path.resolve(
/** @type {Compiler} */
(this.compiler).outputPath,
this.opts.reportFilename || "report.json",
),
compressionAlgorithm: this.opts.compressionAlgorithm,
bundleDir: this.getBundleDirFromCompiler(),
outputFs: this.getOutputFsFromCompiler(),
logger: this.logger,
excludeAssets: this.opts.excludeAssets,
});
}
/**
* @param {StatsCompilation} stats stats
* @returns {Promise<void>}
*/
async generateStaticReport(stats) {
await viewer.generateReport(stats, {
openBrowser: this.opts.openAnalyzer,
reportFilename: path.resolve(
/** @type {Compiler} */
(this.compiler).outputPath,
this.opts.reportFilename || "report.html",
),
reportTitle: this.opts.reportTitle,
compressionAlgorithm: this.opts.compressionAlgorithm,
bundleDir: this.getBundleDirFromCompiler(),
outputFs: this.getOutputFsFromCompiler(),
logger: this.logger,
defaultSizes: this.opts.defaultSizes,
excludeAssets: this.opts.excludeAssets,
});
}
getBundleDirFromCompiler() {
return /** @type {Compiler} */ (this.compiler).outputPath;
}
/**
* Returns the compiler's outputFileSystem if it differs from the native fs
* and supports reading files (e.g. memfs used by webpack-dev-server),
* otherwise returns null to fall back to the native fs.
*
* @returns {OutputFileSystem | null}
*/
getOutputFsFromCompiler() {
const outputFs = /** @type {Compiler} */ (this.compiler).outputFileSystem;
if (
outputFs &&
outputFs !== fs &&
typeof /** @type {EXPECTED_ANY} */ (outputFs).readFileSync === "function"
) {
return /** @type {OutputFileSystem} */ (outputFs);
}
return null;
}
}
module.exports = BundleAnalyzerPlugin;