319 lines
10 KiB
JavaScript
319 lines
10 KiB
JavaScript
#!/usr/bin/env node
|
||
/**
|
||
* 死代码扫描:从入口出发对 src 做模块依赖图可达性分析。
|
||
*
|
||
* 判定口径
|
||
* - 静态可达:从入口(src/main.ts)经 import / export-from / import() / require() 能到达
|
||
* - glob 兜底:被 import.meta.glob(...) 模式匹配到(构建期收集,运行时按后端菜单动态取用)
|
||
* - 死代码 :以上两类都不属于
|
||
*
|
||
* 用法:node scripts/find-unused-modules.mjs [项目根目录] [--views-only]
|
||
*/
|
||
import fs from 'node:fs'
|
||
import path from 'node:path'
|
||
|
||
const args = process.argv.slice(2)
|
||
const viewsOnly = args.includes('--views-only')
|
||
const rootArg = args.find((a) => !a.startsWith('--'))
|
||
const ROOT = rootArg ? path.resolve(rootArg) : process.cwd()
|
||
const SRC = path.join(ROOT, 'src')
|
||
const ENTRIES = [path.join(SRC, 'main.ts')]
|
||
|
||
const WALK_EXT = new Set(['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.vue', '.scss', '.css'])
|
||
const RESOLVE_EXT = ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.vue', '.json', '.scss', '.css', '.svg']
|
||
const INDEX_EXT = ['.ts', '.js', '.vue']
|
||
const SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'dist-ssr', '.vite'])
|
||
|
||
/* ---------- 文件遍历 ---------- */
|
||
function walk(dir, out = []) {
|
||
let entries
|
||
try {
|
||
entries = fs.readdirSync(dir, { withFileTypes: true })
|
||
} catch {
|
||
return out
|
||
}
|
||
for (const e of entries) {
|
||
const full = path.join(dir, e.name)
|
||
if (e.isDirectory()) {
|
||
if (SKIP_DIRS.has(e.name)) continue
|
||
walk(full, out)
|
||
} else {
|
||
const ext = path.extname(e.name)
|
||
if (WALK_EXT.has(ext) || e.name.endsWith('.d.ts')) out.push(full)
|
||
}
|
||
}
|
||
return out
|
||
}
|
||
|
||
/* ---------- 注释剥离(保留字符串字面量,避免 https:// 被误删) ---------- */
|
||
function stripComments(code) {
|
||
let out = ''
|
||
let i = 0
|
||
const n = code.length
|
||
while (i < n) {
|
||
const c = code[i]
|
||
const next = code[i + 1]
|
||
if (c === '/' && next === '/') {
|
||
while (i < n && code[i] !== '\n') i++
|
||
continue
|
||
}
|
||
if (c === '/' && next === '*') {
|
||
i += 2
|
||
while (i < n && !(code[i] === '*' && code[i + 1] === '/')) i++
|
||
i += 2
|
||
continue
|
||
}
|
||
if (c === '"' || c === "'" || c === '`') {
|
||
const q = c
|
||
out += c
|
||
i++
|
||
while (i < n) {
|
||
if (code[i] === '\\') {
|
||
out += code[i] + code[i + 1]
|
||
i += 2
|
||
continue
|
||
}
|
||
out += code[i]
|
||
if (code[i] === q) {
|
||
i++
|
||
break
|
||
}
|
||
i++
|
||
}
|
||
continue
|
||
}
|
||
out += c
|
||
i++
|
||
}
|
||
return out
|
||
}
|
||
|
||
const SPEC_RES = [
|
||
/import\s*\(\s*['"]([^'"]+)['"]\s*\)/g, // 动态 import
|
||
/\bfrom\s*['"]([^'"]+)['"]/g, // import ... from / export ... from
|
||
/\bimport\s+['"]([^'"]+)['"]/g, // 副作用 import
|
||
/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g,
|
||
/new\s+URL\s*\(\s*['"]([^'"]+)['"]/g,
|
||
/@use\s+['"]([^'"]+)['"]/g, // SCSS
|
||
/@forward\s+['"]([^'"]+)['"]/g,
|
||
]
|
||
const GLOB_RE = /import\.meta\.glob(?:Eager)?\s*\(\s*['"]([^'"]+)['"]/g
|
||
|
||
function scanFile(file) {
|
||
const raw = fs.readFileSync(file, 'utf8')
|
||
const code = stripComments(raw)
|
||
const specs = new Set()
|
||
for (const re of SPEC_RES) {
|
||
re.lastIndex = 0
|
||
let m
|
||
while ((m = re.exec(code))) specs.add(m[1])
|
||
}
|
||
const globs = []
|
||
GLOB_RE.lastIndex = 0
|
||
let g
|
||
while ((g = GLOB_RE.exec(code))) globs.push(g[1])
|
||
return { specs: [...specs], globs }
|
||
}
|
||
|
||
/* ---------- 说明符解析 ---------- */
|
||
function resolveSpec(spec, fromFile) {
|
||
if (!spec || typeof spec !== 'string') return null
|
||
let base = null
|
||
const s = spec.split('?')[0].split('#')[0]
|
||
if (s.startsWith('@/')) base = path.join(SRC, s.slice(2))
|
||
else if (s.startsWith('~@/')) base = path.join(SRC, s.slice(3))
|
||
else if (s.startsWith('./') || s.startsWith('../')) base = path.resolve(path.dirname(fromFile), s)
|
||
else return null
|
||
|
||
const candidates = [base]
|
||
for (const ext of RESOLVE_EXT) candidates.push(base + ext)
|
||
// 注意:目录名可能自带点号(api/order.packing、api/waybill.warehouse),
|
||
// 不能用 path.extname 判断,必须比对已知扩展名白名单
|
||
const hasKnownExt = RESOLVE_EXT.includes(path.extname(base).toLowerCase())
|
||
if (!hasKnownExt) for (const ext of INDEX_EXT) candidates.push(path.join(base, 'index' + ext))
|
||
for (const c of candidates) {
|
||
try {
|
||
if (fs.statSync(c).isFile()) return path.normalize(c)
|
||
} catch {
|
||
/* ignore */
|
||
}
|
||
}
|
||
return null
|
||
}
|
||
|
||
/* ---------- glob 模式 → 正则 ---------- */
|
||
function globToRegExp(pattern) {
|
||
let p = pattern
|
||
// 统一成相对项目根的路径(@/ 与 / 都指向 src)
|
||
if (p.startsWith('@/')) p = 'src/' + p.slice(2)
|
||
else if (p.startsWith('~@/')) p = 'src/' + p.slice(3)
|
||
p = p.replace(/^\//, '')
|
||
let re = ''
|
||
for (let i = 0; i < p.length; i++) {
|
||
const c = p[i]
|
||
if (c === '*' && p[i + 1] === '*') {
|
||
re += '[\\s\\S]*'
|
||
i++
|
||
if (p[i + 1] === '/') i++
|
||
continue
|
||
}
|
||
if (c === '*') {
|
||
re += '[^/]*'
|
||
continue
|
||
}
|
||
re += c.replace(/[.+^${}()|[\]\\]/g, '\\$&')
|
||
}
|
||
return new RegExp('^' + re + '$')
|
||
}
|
||
|
||
/* ---------- 主流程 ---------- */
|
||
const allFiles = walk(SRC)
|
||
const rel = (f) => path.relative(ROOT, f).replace(/\\/g, '/')
|
||
|
||
const reachable = new Set()
|
||
const globOnly = new Set()
|
||
const queue = []
|
||
const unresolvedSpecs = []
|
||
|
||
for (const f of ENTRIES) {
|
||
if (!fs.existsSync(f)) {
|
||
console.error(`入口不存在: ${f}`)
|
||
process.exit(1)
|
||
}
|
||
reachable.add(path.normalize(f))
|
||
queue.push(path.normalize(f))
|
||
}
|
||
|
||
const globMatchers = []
|
||
const fileCache = new Map()
|
||
|
||
while (queue.length) {
|
||
const file = queue.pop()
|
||
let scanned = fileCache.get(file)
|
||
if (!scanned) {
|
||
scanned = scanFile(file)
|
||
fileCache.set(file, scanned)
|
||
}
|
||
for (const spec of scanned.specs) {
|
||
const resolved = resolveSpec(spec, file)
|
||
if (!resolved) {
|
||
// 只抱怨“本应能解析”的路径(@/ 与相对路径)
|
||
if (spec.startsWith('@/') || spec.startsWith('~/') || spec.startsWith('~@/')) {
|
||
unresolvedSpecs.push(`${rel(file)} -> ${spec}`)
|
||
}
|
||
continue
|
||
}
|
||
if (!reachable.has(resolved)) {
|
||
reachable.add(resolved)
|
||
if (WALK_EXT.has(path.extname(resolved).toLowerCase())) queue.push(resolved)
|
||
}
|
||
}
|
||
for (const pattern of scanned.globs) {
|
||
globMatchers.push({ from: file, pattern, re: globToRegExp(pattern) })
|
||
}
|
||
}
|
||
|
||
for (const f of allFiles) {
|
||
if (reachable.has(path.normalize(f))) continue
|
||
if (f.endsWith('.d.ts')) continue
|
||
const r = rel(f)
|
||
if (globMatchers.some((g) => g.re.test(r))) globOnly.add(path.normalize(f))
|
||
}
|
||
|
||
/* ---------- 输出 ---------- */
|
||
const sizeOf = (f) => {
|
||
try {
|
||
return fs.statSync(f).size
|
||
} catch {
|
||
return 0
|
||
}
|
||
}
|
||
const kb = (n) => (n / 1024).toFixed(1) + ' KB'
|
||
const norm = (f) => path.normalize(f)
|
||
|
||
const dead = allFiles.filter((f) => !reachable.has(norm(f)) && !globOnly.has(norm(f)) && !f.endsWith('.d.ts'))
|
||
const deadViews = dead.filter((f) => rel(f).startsWith('src/views/') && f.endsWith('.vue'))
|
||
const deadOther = dead.filter((f) => !(rel(f).startsWith('src/views/') && f.endsWith('.vue')))
|
||
|
||
function groupByDir(files, depth = 3) {
|
||
const map = new Map()
|
||
for (const f of files) {
|
||
const r = rel(f)
|
||
const seg = r.split('/').slice(0, depth).join('/')
|
||
if (!map.has(seg)) map.set(seg, [])
|
||
map.get(seg).push(f)
|
||
}
|
||
return [...map.entries()].sort((a, b) => b[1].length - a[1].length)
|
||
}
|
||
|
||
console.log('='.repeat(72))
|
||
console.log(`扫描根目录:${ROOT}`)
|
||
console.log(`src 下模块总数:${allFiles.length} 静态可达:${reachable.size} 仅 glob 兜底:${globOnly.size} 死代码:${dead.length}`)
|
||
console.log('='.repeat(72))
|
||
|
||
if (deadViews.length) {
|
||
console.log(`\n## 未被引用的页面 (.vue):${deadViews.length} 个,合计 ${kb(deadViews.reduce((s, f) => s + sizeOf(f), 0))}\n`)
|
||
for (const [dir, files] of groupByDir(deadViews)) {
|
||
console.log(`● ${dir} (${files.length} 个, ${kb(files.reduce((s, f) => s + sizeOf(f), 0))})`)
|
||
for (const f of files.sort()) console.log(` ${rel(f).replace('src/views/', '')} ${kb(sizeOf(f))}`)
|
||
}
|
||
}
|
||
|
||
if (globOnly.size) {
|
||
const gv = [...globOnly].filter((f) => f.endsWith('.vue'))
|
||
console.log(`\n## 仅被 import.meta.glob 兜底匹配的页面:${gv.length} 个(无法静态判定,需核对后端菜单 component 字段)\n`)
|
||
for (const [dir, files] of groupByDir(gv)) console.log(` ${dir} (${files.length} 个)`)
|
||
}
|
||
|
||
if (!viewsOnly) {
|
||
console.log(`\n## 未被引用的非页面文件:${deadOther.length} 个,合计 ${kb(deadOther.reduce((s, f) => s + sizeOf(f), 0))}\n`)
|
||
for (const [dir, files] of groupByDir(deadOther)) {
|
||
console.log(`● ${dir} (${files.length} 个, ${kb(files.reduce((s, f) => s + sizeOf(f), 0))})`)
|
||
for (const f of files.sort()) console.log(` ${rel(f).replace('src/', '')} ${kb(sizeOf(f))}`)
|
||
}
|
||
}
|
||
|
||
if (unresolvedSpecs.length) {
|
||
const uniq = [...new Set(unresolvedSpecs)]
|
||
console.log(`\n## 无法解析的 @/ 引用:${uniq.length} 条(疑似路径写错或文件已删)\n`)
|
||
for (const u of uniq.slice(0, 100)) console.log(' ' + u)
|
||
}
|
||
|
||
/* 机器可读输出 */
|
||
const aggregate = (files) => {
|
||
const m = {}
|
||
for (const f of files) {
|
||
const seg = rel(f).split('/').slice(0, 4).join('/')
|
||
if (!m[seg]) m[seg] = { count: 0, bytes: 0 }
|
||
m[seg].count += 1
|
||
m[seg].bytes += sizeOf(f)
|
||
}
|
||
return m
|
||
}
|
||
|
||
console.log('\n## 目录级汇总(按死代码文件数降序,便于分批删除)\n')
|
||
for (const [dir, v] of Object.entries(aggregate([...dead, ...globOnly])).sort((a, b) => b[1].count - a[1].count)) {
|
||
console.log(` ${dir} ${v.count} 个 / ${kb(v.bytes)}`)
|
||
}
|
||
|
||
const outFile = path.join(ROOT, 'unused-report.json')
|
||
fs.writeFileSync(
|
||
outFile,
|
||
JSON.stringify(
|
||
{
|
||
scannedAt: new Date().toISOString(),
|
||
totals: { all: allFiles.length, reachable: reachable.size, globOnly: globOnly.size, dead: dead.length },
|
||
deadViews: deadViews.map(rel),
|
||
deadOthers: deadOther.map(rel),
|
||
globOnlyViews: [...globOnly].filter((f) => f.endsWith('.vue')).map(rel),
|
||
globOnlyOthers: [...globOnly].filter((f) => !f.endsWith('.vue')).map(rel),
|
||
aggregate: aggregate([...dead, ...globOnly]),
|
||
unresolvedSpecs: [...new Set(unresolvedSpecs)],
|
||
},
|
||
null,
|
||
2
|
||
),
|
||
'utf8'
|
||
)
|
||
console.log(`\n完整结果已写入 ${rel(outFile)}`)
|