vite-bundle-explorer 0.3.2 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -7,6 +7,7 @@ Bundle analyzer and visualizer tool for vite.
7
7
  - ✅ Chunk treemap
8
8
  - ✅ Module import graph
9
9
  - ✅ Detect duplicated dependencies
10
+ - ✅ Run checks during build
10
11
 
11
12
  ![preview](https://raw.githubusercontent.com/Solant/vite-bundle-explorer/refs/heads/main/preview.gif)
12
13
 
@@ -69,3 +70,5 @@ export default defineConfig({
69
70
  | `reportDirectoryName` | `string` | `"bundle-report"` | Name of the output directory |
70
71
  | `emitHtml` | `boolean` | `true` | Generate interactive HTML report |
71
72
  | `emitJson` | `boolean` | `false` | Generate `stats.json` file |
73
+ | `check` | `boolean` | `true` | Run report checks during build |
74
+ | `failOnWarning` | `boolean` | `false` | Cancel build if bundle has any report warnings |
@@ -1,13 +1,15 @@
1
- import { type Plugin } from 'vite';
1
+ import { Plugin } from "vite";
2
2
 
3
+ //#region plugin/stats-plugin.d.ts
3
4
  interface StatsPluginOptions {
4
5
  enabled?: boolean;
5
6
  reportDirectoryName?: string;
6
7
  reportCompressedSize?: boolean;
7
8
  emitHtml?: boolean;
8
9
  emitJson?: boolean;
10
+ check?: boolean;
11
+ failOnWarning?: boolean;
9
12
  }
10
-
11
- declare function statsPlugin(options?: StatsPluginOptions): Plugin;
12
-
13
- export { statsPlugin };
13
+ declare function statsPlugin(options?: StatsPluginOptions): Plugin<any>;
14
+ //#endregion
15
+ export { statsPlugin };
@@ -0,0 +1,174 @@
1
+ import { join } from "node:path";
2
+ import { gzip } from "node:zlib";
3
+ import { promisify } from "node:util";
4
+ import fs from "node:fs/promises";
5
+ import { fileURLToPath } from "node:url";
6
+
7
+ //#region src/entities/bundle-stats/index.ts
8
+ function isDependency(moduleFileName) {
9
+ return moduleFileName.startsWith("node_modules");
10
+ }
11
+ function getModuleDependencyName(moduleFileName) {
12
+ if (!isDependency(moduleFileName)) return "";
13
+ if (moduleFileName.startsWith("node_modules/.pnpm")) {
14
+ const parts$1 = moduleFileName.split("/");
15
+ if (parts$1[4].startsWith("@")) return `${parts$1[4]}/${parts$1[5]}`;
16
+ else return parts$1[4];
17
+ }
18
+ const parts = moduleFileName.split("/");
19
+ const index = parts.lastIndexOf("node_modules");
20
+ if (parts[index + 1].startsWith("@")) return `${parts[index + 1]}/${parts[index + 2]}`;
21
+ else return parts[index + 1];
22
+ }
23
+
24
+ //#endregion
25
+ //#region src/features/overview/model/overview.ts
26
+ function getBundleOverview(stats) {
27
+ const numberOfChunks = stats.chunks.length;
28
+ let numberOfModules = 0;
29
+ let numberOfVirtualModules = 0;
30
+ for (const chunk of stats.chunks) {
31
+ numberOfModules += chunk.modules.length;
32
+ for (const mod of chunk.modules) if (mod.virtual) numberOfVirtualModules += 1;
33
+ }
34
+ const dependencies = /* @__PURE__ */ new Map();
35
+ for (const module of stats.moduleFileNames) {
36
+ const dep = getModuleDependencyName(module);
37
+ if (!dep) continue;
38
+ const index = module.lastIndexOf(`node_modules/${dep}`);
39
+ const entry = dependencies.get(dep);
40
+ if (entry) {
41
+ if (!entry.indices.includes(index)) entry.indices.push(index);
42
+ } else dependencies.set(dep, { indices: [index] });
43
+ }
44
+ const duplicatedDependencies = [];
45
+ for (const [dep, entry] of dependencies) if (entry.indices.length > 1) duplicatedDependencies.push({
46
+ name: dep,
47
+ count: entry.indices.length
48
+ });
49
+ return {
50
+ numberOfModules,
51
+ numberOfVirtualModules,
52
+ numberOfChunks,
53
+ numberOfDependencies: dependencies.size,
54
+ duplicatedDependencies,
55
+ hasWarnings: duplicatedDependencies.length > 0
56
+ };
57
+ }
58
+
59
+ //#endregion
60
+ //#region plugin/stats-plugin.ts
61
+ const compress = promisify(gzip);
62
+ const REPORT_DIR_NAME = "bundle-report";
63
+ function upsertNodeIndex(nodes, item) {
64
+ const index = nodes.indexOf(item);
65
+ return index === -1 ? nodes.push(item) - 1 : index;
66
+ }
67
+ function statsPlugin(options) {
68
+ const emitHtml = options?.emitHtml ?? true;
69
+ const emitJson = options?.emitJson ?? false;
70
+ const check = options?.check ?? true;
71
+ const failOnWarning = options?.failOnWarning ?? false;
72
+ let root = process.cwd();
73
+ let enabled = options?.enabled ?? true;
74
+ function truncatePath(filePath) {
75
+ let index = 0;
76
+ const normalizedPath = filePath.replaceAll("\0", "");
77
+ if (root && normalizedPath.startsWith(root)) index = root.length;
78
+ return index > 0 ? normalizedPath.substring(index + 1) : normalizedPath;
79
+ }
80
+ const edges = /* @__PURE__ */ new Set();
81
+ const stats = {
82
+ chunks: [],
83
+ importGraph: { edges: [] },
84
+ moduleFileNames: []
85
+ };
86
+ return {
87
+ name: "stats-plugin",
88
+ configResolved(config) {
89
+ enabled = enabled && config.env.PROD;
90
+ },
91
+ resolveId: {
92
+ order: "pre",
93
+ async handler(source, importer, options$1) {
94
+ if (!enabled) return;
95
+ if (!importer) return;
96
+ const result = await this.resolve(source, importer, {
97
+ ...options$1,
98
+ skipSelf: true
99
+ });
100
+ if (!result) return;
101
+ const parent = upsertNodeIndex(stats.moduleFileNames, truncatePath(importer));
102
+ const child = upsertNodeIndex(stats.moduleFileNames, truncatePath(result.id));
103
+ edges.add(`${parent},${child}`);
104
+ }
105
+ },
106
+ generateBundle: { async handler(_options, bundle) {
107
+ if (!enabled) return;
108
+ for (const [_name, chunk] of Object.entries(bundle)) {
109
+ if (chunk.type !== "chunk") continue;
110
+ const currentChunk = {
111
+ fileName: chunk.fileName,
112
+ modules: [],
113
+ minifiedLength: -1,
114
+ compressedLength: -1
115
+ };
116
+ stats.chunks.push(currentChunk);
117
+ for (const [moduleName, mod] of Object.entries(chunk.modules)) {
118
+ const fileName = truncatePath(moduleName);
119
+ currentChunk.modules.push({
120
+ fileNameIndex: upsertNodeIndex(stats.moduleFileNames, fileName),
121
+ renderedLength: mod.renderedLength,
122
+ virtual: moduleName.startsWith("\0") ? true : void 0
123
+ });
124
+ }
125
+ }
126
+ stats.importGraph.edges = Array.from(edges).map((edge) => {
127
+ const pair = edge.split(",");
128
+ return [Number.parseInt(pair[0], 10), Number.parseInt(pair[1], 10)];
129
+ });
130
+ } },
131
+ async writeBundle(_options, bundle) {
132
+ for (const [_name, chunk] of Object.entries(bundle)) {
133
+ if (chunk.type !== "chunk") continue;
134
+ const c = stats.chunks.find((c$1) => c$1.fileName === chunk.fileName);
135
+ if (!c) continue;
136
+ c.minifiedLength = chunk.code.length;
137
+ c.compressedLength = (await compress(chunk.code)).length;
138
+ }
139
+ },
140
+ async closeBundle(error) {
141
+ if (!enabled || error) return;
142
+ enabled = false;
143
+ const target = join(root, options?.reportDirectoryName ?? REPORT_DIR_NAME);
144
+ try {
145
+ if ((await fs.stat(target)).isDirectory()) await fs.rm(target, { recursive: true });
146
+ } catch (e) {}
147
+ await fs.mkdir(target);
148
+ if (emitHtml) {
149
+ const source = join(fileURLToPath(import.meta.url), "..", "dist-ui");
150
+ const names = await fs.readdir(source);
151
+ await Promise.all(names.map((name) => {
152
+ return fs.cp(join(source, name), join(target, name), { recursive: true });
153
+ }));
154
+ let html = await fs.readFile(join(target, "index.html"), "utf-8");
155
+ html = html.replace("%BUNDLE_STATS%", JSON.stringify(stats).replaceAll("'", "\\'"));
156
+ fs.writeFile(join(target, "index.html"), html);
157
+ }
158
+ if (emitJson) fs.writeFile(join(target, "stats.json"), JSON.stringify(stats, null, 2));
159
+ console.log(`Bundle stats saved to ${target}`);
160
+ if (emitHtml) console.log(`Run "npx vite-bundle-explorer ${target}" to view the stats`);
161
+ if (check) {
162
+ const report = getBundleOverview(stats);
163
+ if (report.duplicatedDependencies.length > 0) {
164
+ this.warn("Output bundle has duplicated dependencies");
165
+ for (const dep of report.duplicatedDependencies) this.warn(`- ${dep.name} has ${dep.count} different versions`);
166
+ }
167
+ if (failOnWarning && report.hasWarnings) throw new Error("[plugin stats-plugin] Cancelling build due to failOnWarning option. Check [plugin stats-plugin] warnings for more details.");
168
+ }
169
+ }
170
+ };
171
+ }
172
+
173
+ //#endregion
174
+ export { statsPlugin };