// main.js —— 30 行级 tree-shaker:按「入口用到的导出」做可达性标记 // 只处理教学用的单行 export 声明;生产实现必须用 AST。 const IMPORT_RE = /import\s*\{([^}]*)\}\s*from\s*['"]([^'"]+)['"];?/g; const SIDE_EFFECT_IMPORT_RE = /import\s*['"]([^'"]+)['"];?/g; const EXPORT_DECL_RE = /^export\s+(?:const|let|var|function|class)\s+([A-Za-z_$][\w$]*)/; function scanImports(source) { const imports = []; for (const m of source.matchAll(IMPORT_RE)) { imports.push({ from: m[2], names: m[1] .split(',') .map((s) => s.trim()) .filter(Boolean) .map((s) => s.split(/\s+as\s+/)[0].trim()), }); } for (const m of source.matchAll(SIDE_EFFECT_IMPORT_RE)) { imports.push({ from: m[1], names: [] }); } return imports; } export function treeShake(entry, modules) { const used = new Map(); // id -> Set | null(null = 全保留) const reachable = new Set(); const queue = [{ id: entry, names: null }]; while (queue.length) { const { id, names } = queue.shift(); if (!Object.hasOwn(modules, id)) continue; if (names === null) used.set(id, null); else { if (!(used.get(id) instanceof Set)) used.set(id, new Set()); for (const name of names) used.get(id).add(name); } if (reachable.has(id)) continue; reachable.add(id); for (const imp of scanImports(modules[id])) { queue.push({ id: imp.from, names: imp.names.length ? imp.names : null }); } } const code = {}; const removed = []; const kept = []; for (const id of reachable) { const names = used.get(id); let source = modules[id]; source = source.replace(IMPORT_RE, (_full, list, from) => { if (names === null) return `import { ${list.trim()} } from '${from}';`; const targetUsed = used.get(from); if (targetUsed === null || targetUsed === undefined) { return `import { ${list.trim()} } from '${from}';`; } const keep = list .split(',') .map((s) => s.trim()) .filter(Boolean) .filter((s) => targetUsed.has(s.split(/\s+as\s+/)[0].trim())); return keep.length ? `import { ${keep.join(', ')} } from '${from}';` : `import '${from}';`; }); const lines = []; for (const line of source.split('\n')) { const match = EXPORT_DECL_RE.exec(line); if (match) { const name = match[1]; const shouldKeep = names === null || names.has(name); if (shouldKeep) { kept.push(name); } else { removed.push(name); continue; } } lines.push(line); } code[id] = lines.join('\n'); } return { code, reachable: [...reachable], removed, kept }; } export const FIXTURES = { './main.js': [ "import { used } from './lib.js';", "import { helper } from './util.js';", 'export function main() { return [used, helper()]; }', ].join('\n'), './lib.js': [ 'export const used = 1;', 'export const unused = 2;', 'export function alsoUnused() { return 3; }', ].join('\n'), './util.js': [ "export function helper() { return 'h'; }", "export function dead() { return 'd'; }", ].join('\n'), }; export function run(log = console.log) { const result = treeShake('./main.js', FIXTURES); log(`可达模块:${result.reachable.join(', ')}`); log(`删除的导出:${result.removed.join(', ') || '(无)'}`); log(`保留的导出:${result.kept.join(', ')}`); log('lib.js 处理后:'); for (const line of result.code['./lib.js'].split('\n')) log(` ${line}`); log('要点:从入口标记用到的导出,未被标记的导出可删除;副作用模块要整块保留。'); return result; }