vite-bundle-explorer 0.3.4 → 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 +77 -26
- package/bin/index.js +1 -0
- package/dist-plugin/esbuild.d.mts +10 -0
- package/dist-plugin/esbuild.mjs +109 -0
- package/dist-plugin/src-CgEHOuup.mjs +41 -0
- package/dist-plugin/{stats-plugin.d.ts → stats-plugin.d.mts} +2 -5
- package/dist-plugin/{stats-plugin.js → stats-plugin.mjs} +20 -71
- package/dist-ui/assets/index-CyISDKh8.js +20 -0
- package/dist-ui/assets/index-q6r_rC1D.css +1 -0
- package/dist-ui/index.html +2 -2
- package/package.json +40 -29
- package/dist-ui/assets/index-D-ZNVfN7.css +0 -1
- package/dist-ui/assets/index-DHfe3O-k.js +0 -63
package/README.md
CHANGED
|
@@ -1,22 +1,21 @@
|
|
|
1
1
|
# vite-bundle-explorer
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A powerful bundle analyzer and visualizer tool for Vite, any other Rollup-compatible bundler, and esbuild.
|
|
4
4
|
|
|
5
|
-
|
|
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
|
-
|
|
7
|
+
[Example report](https://solant.me/demo/vite-bundle-explorer)
|
|
13
8
|
|
|
14
|
-
##
|
|
9
|
+
## Why Choose `vite-bundle-explorer`?
|
|
15
10
|
|
|
16
|
-
|
|
11
|
+
While other bundle analysis tools exist for the Vite ecosystem, this package offers a deeper level of insight and broader set of features:
|
|
17
12
|
|
|
18
|
-
-
|
|
19
|
-
-
|
|
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.
|
|
20
19
|
|
|
21
20
|
## Usage
|
|
22
21
|
|
|
@@ -28,8 +27,9 @@ npm install -D vite-bundle-explorer
|
|
|
28
27
|
# pnpm add -D vite-bundle-explorer
|
|
29
28
|
```
|
|
30
29
|
|
|
31
|
-
|
|
32
|
-
|
|
30
|
+
Register the plugin (config name depends on your bundler, here is an example for `vite`).
|
|
31
|
+
|
|
32
|
+
### vite, rollup, rolldown, tsdown and other Rollup-compatible bundlers
|
|
33
33
|
|
|
34
34
|
```javascript
|
|
35
35
|
import { defineConfig } from 'vite';
|
|
@@ -43,13 +43,46 @@ export default defineConfig({
|
|
|
43
43
|
});
|
|
44
44
|
```
|
|
45
45
|
|
|
46
|
-
|
|
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
|
+
|
|
79
|
+
Once your build is complete, you can use CLI or any static file server to see the interactive visualization.
|
|
47
80
|
|
|
48
81
|
```shell
|
|
49
|
-
npx vite-bundle-explorer
|
|
82
|
+
npx vite-bundle-explorer bundle-report
|
|
50
83
|
```
|
|
51
84
|
|
|
52
|
-
##
|
|
85
|
+
## Configuration
|
|
53
86
|
|
|
54
87
|
You can pass options to stats plugin
|
|
55
88
|
|
|
@@ -63,12 +96,30 @@ export default defineConfig({
|
|
|
63
96
|
});
|
|
64
97
|
```
|
|
65
98
|
|
|
66
|
-
|
|
|
67
|
-
|
|
68
|
-
| `enabled` | `boolean` | `true` |
|
|
69
|
-
| `reportCompressedSize` | `boolean` | `true` | Calculate compressed size of chunks.
|
|
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
|
|
99
|
+
| Option | Type | Default | Description |
|
|
100
|
+
|------------------------|-----------|-------------------|-----------------------------------------------------------------------------------------------------------|
|
|
101
|
+
| `enabled` | `boolean` | `true` | Disable stats collection and report generation. This option is disabled automatically for `vite dev` mode |
|
|
102
|
+
| `reportCompressedSize` | `boolean` | `true` | Calculate compressed size of chunks. May slightly increase build time. |
|
|
103
|
+
| `reportDirectoryName` | `string` | `"bundle-report"` | Name of the output directory |
|
|
104
|
+
| `emitHtml` | `boolean` | `true` | Generate a standalone interactive HTML report |
|
|
105
|
+
| `emitJson` | `boolean` | `false` | Generate raw `stats.json` file |
|
|
106
|
+
| `check` | `boolean` | `true` | Run report checks during the build process |
|
|
107
|
+
| `failOnWarning` | `boolean` | `false` | Cancel build if bundle has any report warnings |
|
|
108
|
+
|
|
109
|
+
Esbuild plugin accepts the same options, except for `enabled` and `reportCompressedSize`, which are not available for esbuild.
|
|
110
|
+
|
|
111
|
+
## CI/CD Integration
|
|
112
|
+
|
|
113
|
+
You can use `vite-bundle-explorer` to run checks in your CI pipeline.
|
|
114
|
+
|
|
115
|
+
To fail the build when duplicate dependencies or other warnings are found, set `failOnWarning` to `true`:
|
|
116
|
+
|
|
117
|
+
```javascript
|
|
118
|
+
export default defineConfig({
|
|
119
|
+
plugins: [
|
|
120
|
+
statsPlugin({
|
|
121
|
+
failOnWarning: true,
|
|
122
|
+
}),
|
|
123
|
+
],
|
|
124
|
+
});
|
|
125
|
+
```
|
package/bin/index.js
CHANGED
|
@@ -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
|
-
|
|
15
|
-
export { statsPlugin };
|
|
11
|
+
export declare function statsPlugin(options?: StatsPluginOptions): Plugin<any>;
|
|
12
|
+
export {};
|
|
@@ -1,63 +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
|
-
|
|
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
|
|
8
|
+
import "vite";
|
|
9
|
+
// src/stats-plugin.ts
|
|
61
10
|
const compress = promisify(gzip);
|
|
62
11
|
const REPORT_DIR_NAME = "bundle-report";
|
|
63
12
|
function upsertNodeIndex(nodes, item) {
|
|
@@ -69,7 +18,7 @@ function statsPlugin(options) {
|
|
|
69
18
|
const emitJson = options?.emitJson ?? false;
|
|
70
19
|
const check = options?.check ?? true;
|
|
71
20
|
const failOnWarning = options?.failOnWarning ?? false;
|
|
72
|
-
|
|
21
|
+
const root = process.cwd();
|
|
73
22
|
let enabled = options?.enabled ?? true;
|
|
74
23
|
function truncatePath(filePath) {
|
|
75
24
|
let index = 0;
|
|
@@ -79,27 +28,31 @@ function statsPlugin(options) {
|
|
|
79
28
|
}
|
|
80
29
|
const edges = /* @__PURE__ */ new Set();
|
|
81
30
|
const stats = {
|
|
31
|
+
entryPoints: [],
|
|
82
32
|
chunks: [],
|
|
83
33
|
importGraph: { edges: [] },
|
|
84
|
-
moduleFileNames: []
|
|
34
|
+
moduleFileNames: [],
|
|
35
|
+
builtInModules: []
|
|
85
36
|
};
|
|
86
37
|
return {
|
|
87
38
|
name: "stats-plugin",
|
|
88
39
|
configResolved(config) {
|
|
89
|
-
enabled
|
|
40
|
+
enabled &&= config.env.PROD;
|
|
90
41
|
},
|
|
91
42
|
resolveId: {
|
|
92
43
|
order: "pre",
|
|
93
|
-
async handler(source, importer,
|
|
44
|
+
async handler(source, importer, resolveOptions) {
|
|
94
45
|
if (!enabled) return;
|
|
95
46
|
if (!importer) return;
|
|
47
|
+
if (stats.entryPoints.length === 0) stats.entryPoints.push(truncatePath(importer));
|
|
96
48
|
const result = await this.resolve(source, importer, {
|
|
97
|
-
...
|
|
49
|
+
...resolveOptions,
|
|
98
50
|
skipSelf: true
|
|
99
51
|
});
|
|
100
52
|
if (!result) return;
|
|
101
53
|
const parent = upsertNodeIndex(stats.moduleFileNames, truncatePath(importer));
|
|
102
54
|
const child = upsertNodeIndex(stats.moduleFileNames, truncatePath(result.id));
|
|
55
|
+
if (isBuiltin(truncatePath(result.id)) && !stats.builtInModules.includes(child)) stats.builtInModules.push(child);
|
|
103
56
|
edges.add(`${parent},${child}`);
|
|
104
57
|
}
|
|
105
58
|
},
|
|
@@ -131,10 +84,10 @@ function statsPlugin(options) {
|
|
|
131
84
|
async writeBundle(_options, bundle) {
|
|
132
85
|
for (const [_name, chunk] of Object.entries(bundle)) {
|
|
133
86
|
if (chunk.type !== "chunk") continue;
|
|
134
|
-
const
|
|
135
|
-
if (!
|
|
136
|
-
|
|
137
|
-
|
|
87
|
+
const chunkStats = stats.chunks.find((c) => c.fileName === chunk.fileName);
|
|
88
|
+
if (!chunkStats) continue;
|
|
89
|
+
chunkStats.minifiedLength = chunk.code.length;
|
|
90
|
+
chunkStats.compressedLength = (await compress(chunk.code)).length;
|
|
138
91
|
}
|
|
139
92
|
},
|
|
140
93
|
async closeBundle(error) {
|
|
@@ -143,14 +96,12 @@ function statsPlugin(options) {
|
|
|
143
96
|
const target = join(root, options?.reportDirectoryName ?? REPORT_DIR_NAME);
|
|
144
97
|
try {
|
|
145
98
|
if ((await fs.stat(target)).isDirectory()) await fs.rm(target, { recursive: true });
|
|
146
|
-
} catch
|
|
99
|
+
} catch {}
|
|
147
100
|
await fs.mkdir(target);
|
|
148
101
|
if (emitHtml) {
|
|
149
102
|
const source = join(fileURLToPath(import.meta.url), "..", "..", "dist-ui");
|
|
150
103
|
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
|
-
}));
|
|
104
|
+
await Promise.all(names.map((name) => fs.cp(join(source, name), join(target, name), { recursive: true })));
|
|
154
105
|
let html = await fs.readFile(join(target, "index.html"), "utf-8");
|
|
155
106
|
html = html.replace("%BUNDLE_STATS%", JSON.stringify(stats).replaceAll("'", "\\'"));
|
|
156
107
|
await fs.writeFile(join(target, "index.html"), html);
|
|
@@ -169,6 +120,4 @@ function statsPlugin(options) {
|
|
|
169
120
|
}
|
|
170
121
|
};
|
|
171
122
|
}
|
|
172
|
-
|
|
173
|
-
//#endregion
|
|
174
|
-
export { statsPlugin };
|
|
123
|
+
export { statsPlugin };
|