1 | "use strict";
|
2 |
|
3 |
|
4 |
|
5 |
|
6 | const { relative, resolve, sep } = require("path");
|
7 | const filesize = require("filesize");
|
8 |
|
9 | const PERCENT_MULTIPLIER = 100;
|
10 | const PERCENT_PRECISION = 3;
|
11 |
|
12 |
|
13 |
|
14 |
|
15 | function _formatFileName(mod) {
|
16 | const { fileName, baseName } = mod;
|
17 |
|
18 |
|
19 | if (!baseName) {
|
20 | return `{green-fg}.${sep}${relative(process.cwd(), resolve(fileName))}{/}`;
|
21 | }
|
22 |
|
23 |
|
24 | let parts = fileName.split(sep);
|
25 |
|
26 | const firstNmIdx = parts.indexOf("node_modules");
|
27 | parts = parts.slice(firstNmIdx);
|
28 |
|
29 |
|
30 | const lastNmIdx = parts.lastIndexOf("node_modules");
|
31 | const isScoped = (parts[lastNmIdx + 1] || "").startsWith("@");
|
32 | parts = parts.slice(0, lastNmIdx + (isScoped ? 3 : 2));
|
33 |
|
34 | return parts.map(part => (part === "node_modules" ? "~" : `{yellow-fg}${part}{/}`)).join(sep);
|
35 | }
|
36 |
|
37 | function _formatPercentage(modSize, assetSize) {
|
38 | const percentage = ((modSize / assetSize) * PERCENT_MULTIPLIER).toPrecision(PERCENT_PRECISION);
|
39 |
|
40 | return `${percentage}%`;
|
41 | }
|
42 |
|
43 | function formatModules(mods) {
|
44 |
|
45 |
|
46 |
|
47 | const assetSize = mods.reduce((count, mod) => count + mod.size.full, 0);
|
48 |
|
49 |
|
50 | const modsMap = mods.reduce((memo, mod) => {
|
51 |
|
52 |
|
53 | const fileName = _formatFileName(mod);
|
54 |
|
55 |
|
56 | memo[fileName] = memo[fileName] || {
|
57 | fileName,
|
58 | num: 0,
|
59 | size: 0
|
60 | };
|
61 | memo[fileName].num += 1;
|
62 | memo[fileName].size += mod.size.full;
|
63 |
|
64 | return memo;
|
65 | }, {});
|
66 |
|
67 | return [].concat(
|
68 | [["Name", "Size", "Percent"]],
|
69 | Object.keys(modsMap)
|
70 | .map(fileName => modsMap[fileName])
|
71 | .sort((a, b) => a.size < b.size)
|
72 | .map(mod => [
|
73 | `${mod.fileName} ${mod.num > 1 ? `(${mod.num})` : ""}`,
|
74 | filesize(mod.size),
|
75 | _formatPercentage(mod.size, assetSize)
|
76 | ])
|
77 | );
|
78 | }
|
79 |
|
80 | module.exports = {
|
81 | formatModules,
|
82 | _formatFileName,
|
83 | _formatPercentage
|
84 | };
|