vite-bundle-explorer 1.0.0 → 1.1.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,18 +1,21 @@
1
1
  # vite-bundle-explorer
2
2
 
3
- A powerful bundle analyzer and visualizer tool for Vite and any other Rollup-compatible bundler.
3
+ A powerful bundle analyzer and visualizer tool for Vite, any other Rollup-compatible bundler, and esbuild.
4
4
 
5
5
  Analyze your bundle size, detect duplicate dependencies, and visualize module graphs to optimize your application's performance.
6
6
 
7
- ## Features
7
+ [Example report](https://solant.me/demo/vite-bundle-explorer)
8
8
 
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.
9
+ ## Why Choose `vite-bundle-explorer`?
14
10
 
15
- [Example report](https://solant.me/demo/vite-bundle-explorer)
11
+ While other bundle analysis tools exist for the Vite ecosystem, this package offers a deeper level of insight and broader set of features:
12
+
13
+ - 📦 **Multi-Bundler Support**: works with any Rollup-compatible bundler like `vite`, `rollup`, `rolldown`, and `tsdown`, plus a dedicated plugin for `esbuild`.
14
+ - 🛠️ **Universal**: supports both applications and libraries.
15
+ - 📊 **Advanced Visualisations:** both an interactive Treemap and a powerful Import Graph.
16
+ - 🔗 **Deep Dependency Tracing:** use "Trace Import" to backtrack the full chain of imports responsible for pulling in any given module.
17
+ - 📏 **Accurate Metrics:** correct chunk size reporting, avoiding known issues in alternative tools.
18
+ - 🛡️ **Build Checks**: run checks during the build process.
16
19
 
17
20
  ## Usage
18
21
 
@@ -26,6 +29,8 @@ npm install -D vite-bundle-explorer
26
29
 
27
30
  Register the plugin (config name depends on your bundler, here is an example for `vite`).
28
31
 
32
+ ### vite, rollup, rolldown, tsdown and other Rollup-compatible bundlers
33
+
29
34
  ```javascript
30
35
  import { defineConfig } from 'vite';
31
36
  import { statsPlugin } from 'vite-bundle-explorer/plugin';
@@ -38,6 +43,39 @@ export default defineConfig({
38
43
  });
39
44
  ```
40
45
 
46
+ ### esbuild
47
+
48
+ `esbuild` is not Rollup-compatible, so it has a dedicated plugin exposed via the `/plugin/esbuild` subpath export:
49
+
50
+ ```javascript
51
+ import { build } from 'esbuild';
52
+ import { statsPlugin } from 'vite-bundle-explorer/plugin/esbuild';
53
+
54
+ await build({
55
+ entryPoints: ['./src/index.js'],
56
+ outdir: 'dist',
57
+ bundle: true,
58
+ plugins: [statsPlugin()],
59
+ });
60
+ ```
61
+
62
+ The plugin requires esbuild `0.9.0` or higher and enables the `metafile` option automatically, so you do not need to set it yourself.
63
+
64
+ #### tsup
65
+
66
+ `tsup` is built on esbuild as well and accepts raw esbuild plugins through its `esbuildPlugins` option:
67
+
68
+ ```javascript
69
+ import { defineConfig } from 'tsup';
70
+ import { statsPlugin } from 'vite-bundle-explorer/plugin/esbuild';
71
+
72
+ export default defineConfig({
73
+ entry: ['src/index.ts'],
74
+ format: ['esm'],
75
+ esbuildPlugins: [statsPlugin()],
76
+ });
77
+ ```
78
+
41
79
  Once your build is complete, you can use CLI or any static file server to see the interactive visualization.
42
80
 
43
81
  ```shell
@@ -68,6 +106,8 @@ export default defineConfig({
68
106
  | `check` | `boolean` | `true` | Run report checks during the build process |
69
107
  | `failOnWarning` | `boolean` | `false` | Cancel build if bundle has any report warnings |
70
108
 
109
+ Esbuild plugin accepts the same options, except for `enabled` and `reportCompressedSize`, which are not available for esbuild.
110
+
71
111
  ## CI/CD Integration
72
112
 
73
113
  You can use `vite-bundle-explorer` to run checks in your CI pipeline.
package/bin/index.js CHANGED
@@ -14,7 +14,6 @@ const mimeTypes = {
14
14
  const server = createServer((req, res) => {
15
15
  const { url } = req;
16
16
 
17
- // eslint-disable-next-line no-undef
18
17
  const root = process.argv[2];
19
18
  const file = path.join(root, url.slice(1) || 'index.html');
20
19
  fs.readFile(file)
@@ -0,0 +1,10 @@
1
+ import { Plugin } from "esbuild";
2
+ interface EsbuildStatsPluginOptions {
3
+ reportDirectoryName?: string;
4
+ emitHtml?: boolean;
5
+ emitJson?: boolean;
6
+ check?: boolean;
7
+ failOnWarning?: boolean;
8
+ }
9
+ export declare function esbuildStatsPlugin(options?: EsbuildStatsPluginOptions): Plugin;
10
+ export {};
@@ -0,0 +1,109 @@
1
+ import { t as getBundleOverview } from "./src-CgEHOuup.mjs";
2
+ import { isBuiltin } from "node:module";
3
+ import { join } from "node:path";
4
+ import { gzip } from "node:zlib";
5
+ import { promisify } from "node:util";
6
+ import fs from "node:fs/promises";
7
+ import { fileURLToPath } from "node:url";
8
+ import "esbuild";
9
+ // src/esbuild.ts
10
+ const compress = promisify(gzip);
11
+ const REPORT_DIR_NAME = "bundle-report";
12
+ function upsertNodeIndex(nodes, item) {
13
+ const index = nodes.indexOf(item);
14
+ return index === -1 ? nodes.push(item) - 1 : index;
15
+ }
16
+ function versionToNumber(version) {
17
+ const [major, minor, patch] = version.split(".").map((i) => Number.parseInt(i, 10));
18
+ if (!Number.isFinite(major) || !Number.isFinite(minor) || !Number.isFinite(patch)) return;
19
+ return major * 1e4 + minor * 100 + patch;
20
+ }
21
+ const SUPPORTED_VERSION = versionToNumber("0.9.0");
22
+ function esbuildStatsPlugin(options) {
23
+ const emitHtml = options?.emitHtml ?? true;
24
+ const emitJson = options?.emitJson ?? false;
25
+ const check = options?.check ?? true;
26
+ const failOnWarning = options?.failOnWarning ?? false;
27
+ return {
28
+ name: "esbuild-stats-plugin",
29
+ setup(build) {
30
+ const version = versionToNumber(build.esbuild.version);
31
+ if (version === void 0) console.warn("[vite-bundle-explorer] Unknown esbuild version, compatibility unknown");
32
+ else if (version < SUPPORTED_VERSION) throw new Error("[vite-bundle-explorer] Unsupported esbuild version, version 0.9.0 or higher is required");
33
+ build.initialOptions.metafile = true;
34
+ build.onEnd(async ({ metafile, outputFiles }) => {
35
+ if (metafile === void 0) throw new Error("metafile is undefined");
36
+ const stats = {
37
+ chunks: [],
38
+ entryPoints: [],
39
+ moduleFileNames: Object.keys(metafile.inputs),
40
+ builtInModules: [],
41
+ importGraph: { edges: [] }
42
+ };
43
+ const edges = /* @__PURE__ */ new Set();
44
+ for (const [path, { imports }] of Object.entries(metafile.inputs)) {
45
+ const source = stats.moduleFileNames.indexOf(path);
46
+ for (const imp of imports) {
47
+ if (imp.external) {
48
+ if (isBuiltin(imp.path)) {
49
+ const target = upsertNodeIndex(stats.moduleFileNames, imp.path);
50
+ if (!stats.builtInModules.includes(target)) stats.builtInModules.push(target);
51
+ edges.add(`${source},${target}`);
52
+ }
53
+ continue;
54
+ }
55
+ const target = stats.moduleFileNames.indexOf(imp.path);
56
+ if (target === -1) console.warn(`[vite-bundle-explorer] Could not find target for ${imp.path}`);
57
+ else edges.add(`${source},${target}`);
58
+ }
59
+ }
60
+ stats.importGraph.edges = Array.from(edges).map((edge) => {
61
+ const [source, target] = edge.split(",");
62
+ return [Number.parseInt(source, 10), Number.parseInt(target, 10)];
63
+ });
64
+ for (const [path, output] of Object.entries(metafile.outputs)) {
65
+ if (path.endsWith(".map")) continue;
66
+ if (output.entryPoint !== void 0 && !stats.entryPoints.includes(output.entryPoint)) stats.entryPoints.push(output.entryPoint);
67
+ const chunk = {
68
+ fileName: path,
69
+ minifiedLength: output.bytes,
70
+ compressedLength: -1,
71
+ modules: Object.entries(output.inputs).map(([input, { bytesInOutput }]) => ({
72
+ fileNameIndex: stats.moduleFileNames.indexOf(input),
73
+ renderedLength: bytesInOutput
74
+ }))
75
+ };
76
+ const contents = outputFiles?.find((file) => file.path === path)?.contents ?? await fs.readFile(path).catch(() => void 0);
77
+ if (contents !== void 0) chunk.compressedLength = (await compress(contents)).length;
78
+ stats.chunks.push(chunk);
79
+ }
80
+ const root = process.cwd();
81
+ const target = join(root, options?.reportDirectoryName ?? REPORT_DIR_NAME);
82
+ try {
83
+ if ((await fs.stat(target)).isDirectory()) await fs.rm(target, { recursive: true });
84
+ } catch {}
85
+ await fs.mkdir(target);
86
+ if (emitHtml) {
87
+ const source = join(fileURLToPath(import.meta.url), "..", "..", "dist-ui");
88
+ const names = await fs.readdir(source);
89
+ await Promise.all(names.map((name) => fs.cp(join(source, name), join(target, name), { recursive: true })));
90
+ let html = await fs.readFile(join(target, "index.html"), "utf-8");
91
+ html = html.replace("%BUNDLE_STATS%", JSON.stringify(stats).replaceAll("'", "\\'"));
92
+ await fs.writeFile(join(target, "index.html"), html);
93
+ }
94
+ if (emitJson) await fs.writeFile(join(target, "stats.json"), JSON.stringify(stats, null, 2));
95
+ console.log(`Bundle stats saved to ${target}`);
96
+ if (emitHtml) console.log(`Run "npx vite-bundle-explorer ${target}" to view the stats`);
97
+ if (check) {
98
+ const report = getBundleOverview(stats);
99
+ if (report.duplicatedDependencies.length > 0) {
100
+ console.warn("Output bundle has duplicated dependencies");
101
+ for (const dep of report.duplicatedDependencies) console.warn(`- ${dep.name} has ${dep.count} different versions`);
102
+ }
103
+ if (failOnWarning && report.hasWarnings) throw new Error("[plugin esbuild-stats-plugin] Cancelling build due to failOnWarning option. Check [plugin esbuild-stats-plugin] warnings for more details.");
104
+ }
105
+ });
106
+ }
107
+ };
108
+ }
109
+ export { esbuildStatsPlugin };
@@ -0,0 +1,41 @@
1
+ // ../shared/src/index.ts
2
+ function isDependency(moduleFileName) {
3
+ return moduleFileName.lastIndexOf("node_modules") !== -1;
4
+ }
5
+ function getModuleDependencyName(moduleFileName) {
6
+ if (!isDependency(moduleFileName)) return "";
7
+ const parts = moduleFileName.split("/");
8
+ const index = parts.lastIndexOf("node_modules");
9
+ if (parts[index + 1].startsWith("@")) return `${parts[index + 1]}/${parts[index + 2]}`;
10
+ return parts[index + 1];
11
+ }
12
+ function getBundleOverview(stats) {
13
+ const numberOfChunks = stats.chunks.length;
14
+ const numberOfModules = stats.moduleFileNames.length;
15
+ let numberOfVirtualModules = 0;
16
+ for (const chunk of stats.chunks) for (const mod of chunk.modules) if (mod.virtual) numberOfVirtualModules += 1;
17
+ const dependencies = /* @__PURE__ */ new Map();
18
+ for (const module of stats.moduleFileNames) {
19
+ const dep = getModuleDependencyName(module);
20
+ if (!dep) continue;
21
+ const index = module.lastIndexOf(`node_modules/${dep}`);
22
+ const entry = dependencies.get(dep);
23
+ if (entry) {
24
+ if (!entry.indices.includes(index)) entry.indices.push(index);
25
+ } else dependencies.set(dep, { indices: [index] });
26
+ }
27
+ const duplicatedDependencies = [];
28
+ for (const [dep, entry] of dependencies) if (entry.indices.length > 1) duplicatedDependencies.push({
29
+ name: dep,
30
+ count: entry.indices.length
31
+ });
32
+ return {
33
+ numberOfModules,
34
+ numberOfVirtualModules,
35
+ numberOfChunks,
36
+ numberOfDependencies: dependencies.size,
37
+ duplicatedDependencies,
38
+ hasWarnings: duplicatedDependencies.length > 0
39
+ };
40
+ }
41
+ export { getBundleOverview as t };
@@ -1,6 +1,4 @@
1
1
  import { Plugin } from "vite";
2
-
3
- //#region plugin/stats-plugin.d.ts
4
2
  interface StatsPluginOptions {
5
3
  enabled?: boolean;
6
4
  reportDirectoryName?: string;
@@ -10,6 +8,5 @@ interface StatsPluginOptions {
10
8
  check?: boolean;
11
9
  failOnWarning?: boolean;
12
10
  }
13
- declare function statsPlugin(options?: StatsPluginOptions): Plugin<any>;
14
- //#endregion
15
- export { statsPlugin };
11
+ export declare function statsPlugin(options?: StatsPluginOptions): Plugin<any>;
12
+ export {};
@@ -1,60 +1,12 @@
1
+ import { t as getBundleOverview } from "./src-CgEHOuup.mjs";
2
+ import { isBuiltin } from "node:module";
1
3
  import { join } from "node:path";
2
4
  import { gzip } from "node:zlib";
3
5
  import { promisify } from "node:util";
4
6
  import fs from "node:fs/promises";
5
7
  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
- 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
- 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
- const numberOfModules = stats.moduleFileNames.length;
29
- let numberOfVirtualModules = 0;
30
- for (const chunk of stats.chunks) for (const mod of chunk.modules) if (mod.virtual) numberOfVirtualModules += 1;
31
- const dependencies = /* @__PURE__ */ new Map();
32
- for (const module of stats.moduleFileNames) {
33
- const dep = getModuleDependencyName(module);
34
- if (!dep) continue;
35
- const index = module.lastIndexOf(`node_modules/${dep}`);
36
- const entry = dependencies.get(dep);
37
- if (entry) {
38
- if (!entry.indices.includes(index)) entry.indices.push(index);
39
- } else dependencies.set(dep, { indices: [index] });
40
- }
41
- const duplicatedDependencies = [];
42
- for (const [dep, entry] of dependencies) if (entry.indices.length > 1) duplicatedDependencies.push({
43
- name: dep,
44
- count: entry.indices.length
45
- });
46
- return {
47
- numberOfModules,
48
- numberOfVirtualModules,
49
- numberOfChunks,
50
- numberOfDependencies: dependencies.size,
51
- duplicatedDependencies,
52
- hasWarnings: duplicatedDependencies.length > 0
53
- };
54
- }
55
-
56
- //#endregion
57
- //#region plugin/stats-plugin.ts
8
+ import "vite";
9
+ // src/stats-plugin.ts
58
10
  const compress = promisify(gzip);
59
11
  const REPORT_DIR_NAME = "bundle-report";
60
12
  function upsertNodeIndex(nodes, item) {
@@ -79,7 +31,8 @@ function statsPlugin(options) {
79
31
  entryPoints: [],
80
32
  chunks: [],
81
33
  importGraph: { edges: [] },
82
- moduleFileNames: []
34
+ moduleFileNames: [],
35
+ builtInModules: []
83
36
  };
84
37
  return {
85
38
  name: "stats-plugin",
@@ -99,6 +52,7 @@ function statsPlugin(options) {
99
52
  if (!result) return;
100
53
  const parent = upsertNodeIndex(stats.moduleFileNames, truncatePath(importer));
101
54
  const child = upsertNodeIndex(stats.moduleFileNames, truncatePath(result.id));
55
+ if (isBuiltin(truncatePath(result.id)) && !stats.builtInModules.includes(child)) stats.builtInModules.push(child);
102
56
  edges.add(`${parent},${child}`);
103
57
  }
104
58
  },
@@ -166,6 +120,4 @@ function statsPlugin(options) {
166
120
  }
167
121
  };
168
122
  }
169
-
170
- //#endregion
171
- export { statsPlugin };
123
+ export { statsPlugin };