177 lines
7.8 KiB
JavaScript
177 lines
7.8 KiB
JavaScript
#!/usr/bin/env node
|
||
/**
|
||
* 产物体检(阶段 8 · 第 6 项「UI chunk 优化」的分析工具):把一个 vite 构建产物
|
||
* 拆成「首屏必须下载什么」+「每个 chunk 里装的是谁的代码」。
|
||
*
|
||
* 为什么要它:`ui` chunk 1216 kB 一直在顶 chunkSizeWarningLimit,但只凭这一行
|
||
* 数字没法判断该不该动、动了有没有收益。要判断必须回答三个问题:
|
||
* 1) 首屏(index.html 的 <script> + modulepreload + 它们的静态 import 闭包)
|
||
* 到底拉了哪些文件——lazy 路由的 chunk 不算首屏,混在一起看会得出错误结论;
|
||
* 2) 这些文件里前十大来源是哪些依赖——不知道是谁占的就不知道能拆什么;
|
||
* 3) 同一个东西在 lazy chunk 里有多少是首屏其实不需要的。
|
||
*
|
||
* 大小口径:raw(磁盘字节)/ gzip / brotli 都给。传输看压缩,parse 看 raw,
|
||
* 两个都要,只看 raw 会高估、只看 gzip 会低估 CPU 成本。
|
||
* 归属口径:用同名 .map 的 mappings 把「产物列区间」映射回源文件,
|
||
* 再按 node_modules 包名 / src 路径聚合。列 ≈ 字节(产物是 ASCII 压缩代码),
|
||
* 这是近似值,但足够定位大头。没有 .map 时只出尺寸表。
|
||
*
|
||
* 用法:
|
||
* node scripts/ui/chunkinfo.mjs [dist 目录] # 默认 frontend/dist
|
||
* node scripts/ui/chunkinfo.mjs frontend/dist-sm # 带 --sourcemap 的产物做归属分析
|
||
*/
|
||
import fs from 'node:fs'
|
||
import path from 'node:path'
|
||
import zlib from 'node:zlib'
|
||
import { fileURLToPath } from 'node:url'
|
||
|
||
const HERE = path.dirname(fileURLToPath(import.meta.url))
|
||
const DIST = path.resolve(process.argv[2] || path.join(HERE, '../../frontend/dist'))
|
||
const ASSETS = path.join(DIST, 'assets')
|
||
|
||
const kb = (n) => (n / 1024).toFixed(2).padStart(8)
|
||
const exists = (p) => fs.existsSync(p)
|
||
|
||
function sizes(file) {
|
||
const buf = fs.readFileSync(file)
|
||
return {
|
||
raw: buf.length,
|
||
gzip: zlib.gzipSync(buf, { level: 9 }).length,
|
||
brotli: zlib.brotliCompressSync(buf).length,
|
||
buf,
|
||
}
|
||
}
|
||
|
||
/* ---------- 1. 首屏闭包:index.html → 静态 import 图 ---------- */
|
||
const html = fs.readFileSync(path.join(DIST, 'index.html'), 'utf8')
|
||
const ref = /(\/assets\/[\w.-]+\.(?:js|css))/g
|
||
const eager = new Set()
|
||
let m
|
||
while ((m = ref.exec(html))) {
|
||
const f = path.join(ASSETS, path.basename(m[1]))
|
||
if (exists(f)) eager.add(path.basename(f))
|
||
}
|
||
/* 沿静态 import / export-from 递归(dynamic import 不算:那是换页时才拉的) */
|
||
const STATIC = /(?:^|[\s;}])import\s+(?:[\w*{}\s,]+\s+from\s+)?["'](\.\/[\w.-]+\.js)["']|(?:^|[\s;}])import\s+["'](\.\/[\w.-]+\.js)["']|(?:^|[\s;}])export\s+(?:[\w*{}\s,]+\s+)?from\s+["'](\.\/[\w.-]+\.js)["']/g
|
||
function closure(seed) {
|
||
const seen = new Set(seed)
|
||
const queue = [...seed]
|
||
while (queue.length) {
|
||
const name = queue.shift()
|
||
const f = path.join(ASSETS, name)
|
||
if (!exists(f) || !name.endsWith('.js')) continue
|
||
const code = fs.readFileSync(f, 'utf8')
|
||
let mm
|
||
while ((mm = STATIC.exec(code))) {
|
||
const dep = path.basename(mm[1] || mm[2] || mm[3])
|
||
if (exists(path.join(ASSETS, dep)) && !seen.has(dep)) { seen.add(dep); queue.push(dep) }
|
||
}
|
||
}
|
||
return seen
|
||
}
|
||
const eagerAll = closure(eager)
|
||
|
||
/* ---------- 2. 尺寸表 ---------- */
|
||
const files = fs.readdirSync(ASSETS).filter((f) => /\.(js|css)$/.test(f)).sort()
|
||
const rows = files.map((f) => ({ f, ...sizes(path.join(ASSETS, f)) }))
|
||
const total = rows.reduce((a, r) => ({ raw: a.raw + r.raw, gzip: a.gzip + r.gzip, brotli: a.brotli + r.brotli }), { raw: 0, gzip: 0, brotli: 0 })
|
||
const eagerRows = rows.filter((r) => eagerAll.has(r.f))
|
||
const eagerTotal = eagerRows.reduce((a, r) => ({ raw: a.raw + r.raw, gzip: a.gzip + r.gzip, brotli: a.brotli + r.brotli }), { raw: 0, gzip: 0, brotli: 0 })
|
||
|
||
console.log('dist:', DIST)
|
||
console.log('\n=== 首屏闭包(index.html 静态引用 + 静态 import 递归)===')
|
||
console.log('文件'.padEnd(44), 'raw kB', 'gzip kB', 'brotli kB')
|
||
for (const r of eagerRows.sort((a, b) => b.raw - a.raw)) {
|
||
console.log(r.f.padEnd(44), kb(r.raw), kb(r.gzip), kb(r.brotli))
|
||
}
|
||
console.log('-'.repeat(72))
|
||
console.log('首屏合计'.padEnd(42), kb(eagerTotal.raw), kb(eagerTotal.gzip), kb(eagerTotal.brotli))
|
||
console.log('全部产物'.padEnd(42), kb(total.raw), kb(total.gzip), kb(total.brotli))
|
||
console.log(`首屏占全部:raw ${(100 * eagerTotal.raw / total.raw).toFixed(1)}% · gzip ${(100 * eagerTotal.gzip / total.gzip).toFixed(1)}%`)
|
||
|
||
console.log('\n=== 全部 chunk(含换页才拉的)===')
|
||
console.log('文件'.padEnd(44), 'raw kB', 'gzip kB', 'brotli kB', '首屏')
|
||
for (const r of rows.sort((a, b) => b.raw - a.raw)) {
|
||
console.log(r.f.padEnd(44), kb(r.raw), kb(r.gzip), kb(r.brotli), eagerAll.has(r.f) ? 'YES' : ' ')
|
||
}
|
||
|
||
/* ---------- 3. 归属分析(需要 .map) ---------- */
|
||
/* source-map VLQ 解码:只需要 generated line / column → source index。 */
|
||
const CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
|
||
const VAL = new Int8Array(128).fill(-64)
|
||
CHARS.split('').forEach((c, i) => { VAL[c.charCodeAt(0)] = i })
|
||
|
||
function decode(line) {
|
||
const segs = []
|
||
let gcol = 0, sidx = 0
|
||
for (const seg of line.split(',')) {
|
||
if (!seg) continue
|
||
const fields = []
|
||
let i = 0
|
||
while (i < seg.length && fields.length < 5) {
|
||
let shift = 0, result = 0, cont = true
|
||
while (cont) {
|
||
const d = VAL[seg.charCodeAt(i++)]
|
||
if (d < 0) { cont = false; break }
|
||
cont = !!(d & 32)
|
||
result |= (d & 31) << shift
|
||
shift += 5
|
||
}
|
||
const neg = result & 1
|
||
result >>= 1
|
||
fields.push(neg ? -result : result)
|
||
}
|
||
gcol += fields[0]
|
||
if (fields.length >= 4) { sidx += fields[1]; segs.push([gcol, sidx]) }
|
||
}
|
||
return segs
|
||
}
|
||
|
||
|
||
const withMaps = rows.filter((r) => r.f.endsWith('.js') && exists(path.join(ASSETS, r.f + '.map')))
|
||
if (!withMaps.length) {
|
||
console.log('\n(产物没有 .map:跳过归属分析。用 `npx vite build --sourcemap --outDir dist-sm` 再跑一次。)')
|
||
} else {
|
||
const agg = new Map()
|
||
const aggByChunk = new Map()
|
||
for (const r of withMaps) {
|
||
const map = JSON.parse(fs.readFileSync(path.join(ASSETS, r.f + '.map'), 'utf8'))
|
||
const srcs = map.sources || []
|
||
const lines = map.mappings.split(';')
|
||
/* 按行取每行最后一个有源的文件,把该行剩余列归给它:
|
||
压缩产物一行常常混了多个源,段级更准但抖动大;行级足够定位大头。 */
|
||
const code = r.buf.toString('utf8').split('\n')
|
||
const own = new Map()
|
||
for (let li = 0; li < lines.length; li++) {
|
||
const segs = decode(lines[li])
|
||
if (!segs.length) { continue }
|
||
const lineLen = Buffer.byteLength(code[li] ?? '', 'utf8') + 1
|
||
let prev = null
|
||
for (const s of segs) {
|
||
if (prev) { const w = Math.max(0, s[0] - prev[0]); own.set(srcs[prev[1]] || '?', (own.get(srcs[prev[1]] || '?') || 0) + w) }
|
||
prev = s
|
||
}
|
||
if (prev) { const w = Math.max(0, lineLen - prev[0]); own.set(srcs[prev[1]] || '?', (own.get(srcs[prev[1]] || '?') || 0) + w) }
|
||
}
|
||
const per = new Map()
|
||
for (const [src, w] of own) {
|
||
const rel = src.split('node_modules/').pop()
|
||
const key = src.includes('node_modules/')
|
||
? 'npm:' + rel.split('/').slice(0, rel.startsWith('@') ? 2 : 1).join('/')
|
||
: 'src:' + src.split('/src/').pop()
|
||
agg.set(key, (agg.get(key) || 0) + w)
|
||
per.set(key, (per.get(key) || 0) + w)
|
||
}
|
||
aggByChunk.set(r.f, per)
|
||
}
|
||
const top = (map, n) => [...map.entries()].sort((a, b) => b[1] - a[1]).slice(0, n)
|
||
console.log('\n=== 全站前 15 大来源(按压缩产物字节近似归属)===')
|
||
for (const [k, v] of top(agg, 15)) console.log(kb(v), 'kB', k)
|
||
for (const [chunk, per] of aggByChunk) {
|
||
if (!eagerAll.has(chunk)) continue
|
||
if (per.size < 8) continue
|
||
console.log(`\n=== 首屏 chunk ${chunk} 前 15 大来源 ===`)
|
||
for (const [k, v] of top(per, 15)) console.log(kb(v), 'kB', k)
|
||
}
|
||
}
|