vite-bundle-explorer 0.3.3 → 1.0.0

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
@@ -1,22 +1,18 @@
1
1
  # vite-bundle-explorer
2
2
 
3
- Bundle analyzer and visualizer tool for vite.
3
+ A powerful bundle analyzer and visualizer tool for Vite and any other Rollup-compatible bundler.
4
4
 
5
- - ✅ Supports both applications and libraries
6
- - ✅ Supports `vite`, `rollup`, `rolldown` and `tsdown`
7
- - ✅ Chunk treemap
8
- - ✅ Module import graph
9
- - ✅ Detect duplicated dependencies
10
- - ✅ Run checks during build
5
+ Analyze your bundle size, detect duplicate dependencies, and visualize module graphs to optimize your application's performance.
11
6
 
12
- ![preview](https://raw.githubusercontent.com/Solant/vite-bundle-explorer/refs/heads/main/preview.gif)
7
+ ## Features
13
8
 
14
- ## How it works
9
+ - ⚡ **Multi-Bundler Support** – Works with any Rollup-compatible bundler like `vite`, `rollup`, `rolldown`, and `tsdown`.
10
+ - 📦 **Universal** – Supports both Applications and Libraries.
11
+ - 📊 **Visual Insights** – Interactive Chunk Treemap and Module Import Graph.
12
+ - 🔍 **Deep Analysis** – Detect duplicated dependencies, trace dependencies to identify exactly _why_ module is bundled.
13
+ - 🛡️ **Build Checks** – Run checks during the build process.
15
14
 
16
- `vite-bundle-explorer` consists of two main parts:
17
-
18
- - Vite Plugin: Gathers detailed build statistics in JSON format
19
- - CLI Utility: Serves a web interface for visualizing the data.
15
+ [Example report](https://solant.me/demo/vite-bundle-explorer)
20
16
 
21
17
  ## Usage
22
18
 
@@ -28,8 +24,7 @@ npm install -D vite-bundle-explorer
28
24
  # pnpm add -D vite-bundle-explorer
29
25
  ```
30
26
 
31
- Next, add the `statsPlugin` to your vite config. This plugin will generate a `stats.json` file in your output directory
32
- on successful build, containing all bundle stats.
27
+ Register the plugin (config name depends on your bundler, here is an example for `vite`).
33
28
 
34
29
  ```javascript
35
30
  import { defineConfig } from 'vite';
@@ -43,13 +38,13 @@ export default defineConfig({
43
38
  });
44
39
  ```
45
40
 
46
- Once your build is complete and `stats.json` is generated, you can launch the web interface using the CLI utility:
41
+ Once your build is complete, you can use CLI or any static file server to see the interactive visualization.
47
42
 
48
43
  ```shell
49
- npx vite-bundle-explorer ./dist/stats.json
44
+ npx vite-bundle-explorer bundle-report
50
45
  ```
51
46
 
52
- ## Options
47
+ ## Configuration
53
48
 
54
49
  You can pass options to stats plugin
55
50
 
@@ -63,12 +58,28 @@ export default defineConfig({
63
58
  });
64
59
  ```
65
60
 
66
- | Parameter | Type | Default | Description |
67
- |------------------------|-----------|-------------------|------------------------------------------------------------------------------------------------------------|
68
- | `enabled` | `boolean` | `true` | Disables stats collection and report generation. This option is disabled automatically for `vite dev` mode |
69
- | `reportCompressedSize` | `boolean` | `true` | Calculate compressed size of chunks. Might affect performance. |
70
- | `reportDirectoryName` | `string` | `"bundle-report"` | Name of the output directory |
71
- | `emitHtml` | `boolean` | `true` | Generate interactive HTML report |
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 |
61
+ | Option | Type | Default | Description |
62
+ |------------------------|-----------|-------------------|-----------------------------------------------------------------------------------------------------------|
63
+ | `enabled` | `boolean` | `true` | Disable stats collection and report generation. This option is disabled automatically for `vite dev` mode |
64
+ | `reportCompressedSize` | `boolean` | `true` | Calculate compressed size of chunks. May slightly increase build time. |
65
+ | `reportDirectoryName` | `string` | `"bundle-report"` | Name of the output directory |
66
+ | `emitHtml` | `boolean` | `true` | Generate a standalone interactive HTML report |
67
+ | `emitJson` | `boolean` | `false` | Generate raw `stats.json` file |
68
+ | `check` | `boolean` | `true` | Run report checks during the build process |
69
+ | `failOnWarning` | `boolean` | `false` | Cancel build if bundle has any report warnings |
70
+
71
+ ## CI/CD Integration
72
+
73
+ You can use `vite-bundle-explorer` to run checks in your CI pipeline.
74
+
75
+ To fail the build when duplicate dependencies or other warnings are found, set `failOnWarning` to `true`:
76
+
77
+ ```javascript
78
+ export default defineConfig({
79
+ plugins: [
80
+ statsPlugin({
81
+ failOnWarning: true,
82
+ }),
83
+ ],
84
+ });
85
+ ```
package/bin/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ /* eslint-disable no-console */
2
3
  import { createServer } from 'node:http';
3
4
  import fs from 'node:fs/promises';
4
5
  import path from 'node:path';
@@ -13,6 +14,7 @@ const mimeTypes = {
13
14
  const server = createServer((req, res) => {
14
15
  const { url } = req;
15
16
 
17
+ // eslint-disable-next-line no-undef
16
18
  const root = process.argv[2];
17
19
  const file = path.join(root, url.slice(1) || 'index.html');
18
20
  fs.readFile(file)
@@ -13,24 +13,21 @@ function getModuleDependencyName(moduleFileName) {
13
13
  if (moduleFileName.startsWith("node_modules/.pnpm")) {
14
14
  const parts$1 = moduleFileName.split("/");
15
15
  if (parts$1[4].startsWith("@")) return `${parts$1[4]}/${parts$1[5]}`;
16
- else return parts$1[4];
16
+ return parts$1[4];
17
17
  }
18
18
  const parts = moduleFileName.split("/");
19
19
  const index = parts.lastIndexOf("node_modules");
20
20
  if (parts[index + 1].startsWith("@")) return `${parts[index + 1]}/${parts[index + 2]}`;
21
- else return parts[index + 1];
21
+ return parts[index + 1];
22
22
  }
23
23
 
24
24
  //#endregion
25
25
  //#region src/features/overview/model/overview.ts
26
26
  function getBundleOverview(stats) {
27
27
  const numberOfChunks = stats.chunks.length;
28
- let numberOfModules = 0;
28
+ const numberOfModules = stats.moduleFileNames.length;
29
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
- }
30
+ for (const chunk of stats.chunks) for (const mod of chunk.modules) if (mod.virtual) numberOfVirtualModules += 1;
34
31
  const dependencies = /* @__PURE__ */ new Map();
35
32
  for (const module of stats.moduleFileNames) {
36
33
  const dep = getModuleDependencyName(module);
@@ -69,7 +66,7 @@ function statsPlugin(options) {
69
66
  const emitJson = options?.emitJson ?? false;
70
67
  const check = options?.check ?? true;
71
68
  const failOnWarning = options?.failOnWarning ?? false;
72
- let root = process.cwd();
69
+ const root = process.cwd();
73
70
  let enabled = options?.enabled ?? true;
74
71
  function truncatePath(filePath) {
75
72
  let index = 0;
@@ -79,6 +76,7 @@ function statsPlugin(options) {
79
76
  }
80
77
  const edges = /* @__PURE__ */ new Set();
81
78
  const stats = {
79
+ entryPoints: [],
82
80
  chunks: [],
83
81
  importGraph: { edges: [] },
84
82
  moduleFileNames: []
@@ -86,15 +84,16 @@ function statsPlugin(options) {
86
84
  return {
87
85
  name: "stats-plugin",
88
86
  configResolved(config) {
89
- enabled = enabled && config.env.PROD;
87
+ enabled &&= config.env.PROD;
90
88
  },
91
89
  resolveId: {
92
90
  order: "pre",
93
- async handler(source, importer, options$1) {
91
+ async handler(source, importer, resolveOptions) {
94
92
  if (!enabled) return;
95
93
  if (!importer) return;
94
+ if (stats.entryPoints.length === 0) stats.entryPoints.push(truncatePath(importer));
96
95
  const result = await this.resolve(source, importer, {
97
- ...options$1,
96
+ ...resolveOptions,
98
97
  skipSelf: true
99
98
  });
100
99
  if (!result) return;
@@ -131,10 +130,10 @@ function statsPlugin(options) {
131
130
  async writeBundle(_options, bundle) {
132
131
  for (const [_name, chunk] of Object.entries(bundle)) {
133
132
  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;
133
+ const chunkStats = stats.chunks.find((c) => c.fileName === chunk.fileName);
134
+ if (!chunkStats) continue;
135
+ chunkStats.minifiedLength = chunk.code.length;
136
+ chunkStats.compressedLength = (await compress(chunk.code)).length;
138
137
  }
139
138
  },
140
139
  async closeBundle(error) {
@@ -143,19 +142,17 @@ function statsPlugin(options) {
143
142
  const target = join(root, options?.reportDirectoryName ?? REPORT_DIR_NAME);
144
143
  try {
145
144
  if ((await fs.stat(target)).isDirectory()) await fs.rm(target, { recursive: true });
146
- } catch (e) {}
145
+ } catch {}
147
146
  await fs.mkdir(target);
148
147
  if (emitHtml) {
149
- const source = join(fileURLToPath(import.meta.url), "..", "dist-ui");
148
+ const source = join(fileURLToPath(import.meta.url), "..", "..", "dist-ui");
150
149
  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
- }));
150
+ await Promise.all(names.map((name) => fs.cp(join(source, name), join(target, name), { recursive: true })));
154
151
  let html = await fs.readFile(join(target, "index.html"), "utf-8");
155
152
  html = html.replace("%BUNDLE_STATS%", JSON.stringify(stats).replaceAll("'", "\\'"));
156
- fs.writeFile(join(target, "index.html"), html);
153
+ await fs.writeFile(join(target, "index.html"), html);
157
154
  }
158
- if (emitJson) fs.writeFile(join(target, "stats.json"), JSON.stringify(stats, null, 2));
155
+ if (emitJson) await fs.writeFile(join(target, "stats.json"), JSON.stringify(stats, null, 2));
159
156
  console.log(`Bundle stats saved to ${target}`);
160
157
  if (emitHtml) console.log(`Run "npx vite-bundle-explorer ${target}" to view the stats`);
161
158
  if (check) {