-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
Copy pathqueryRollupStats.js
78 lines (63 loc) · 2.47 KB
/
queryRollupStats.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
"use strict";
/* eslint-disable no-console */
// This script queries a stats.json file generated by rollup-plugin-visualizer to find all reference paths to a specific module.
// This helps understand why a module is not being tree shaken from the bundle.
// Example: node queryRollupStats.js someModule.js
const fs = require("fs");
const path = require("path");
const chalk = require("chalk");
function stringToColorHash(str) {
// Simple hash function
let hash = 0;
for (let i = 0; i < str.length; i++) {
hash = str.charCodeAt(i) + ((hash << 5) - hash);
}
// Convert hash to 6-digit hexadecimal string
let color = "#";
for (let i = 0; i < 3; i++) {
const value = (hash >> (i * 8)) & 0xff;
color += value.toString(16).substring(-2);
}
return color;
}
function queryRollupStats(filter, maxDepth, statsFilePath) {
if (!maxDepth) {
maxDepth = Number.POSITIVE_INFINITY;
}
const { nodeMetas } = JSON.parse(fs.readFileSync(statsFilePath, "utf8"));
const referenceStack = [];
const seenStacks = new Set();
function traverse(uid, depth) {
const node = nodeMetas[uid];
referenceStack.push(node.id);
if (node.importedBy.length === 0 || depth >= maxDepth) {
const stack = referenceStack.join(" -> ");
if (!seenStacks.has(stack)) {
seenStacks.add(stack);
for (let reference of referenceStack) {
const folder = path.dirname(reference);
const file = path.basename(reference);
reference = chalk.hex(stringToColorHash(reference))(`${folder}/${chalk.bold(file)}`);
console.log(reference);
}
console.log();
}
} else {
for (const importedBy of node.importedBy) {
traverse(importedBy.uid, depth + 1);
}
}
referenceStack.pop();
}
const matches = Object.entries(nodeMetas)
.filter(([key, value]) => value.id.toLowerCase().includes(filter.toLocaleLowerCase()))
.map(([key, value]) => key);
matches.forEach((match) => traverse(match, 1));
}
if (require.main === module) {
const [scriptPath, filter, maxDepth, statsFilePath = "stats.json"] = process.argv.slice(1);
queryRollupStats(filter, maxDepth, statsFilePath);
}
module.exports = {
queryRollupStats,
};