import test from 'node:test' import assert from 'node:assert/strict' import { readdirSync, statSync } from 'node:fs' import { join } from 'node:path' import { readSource } from './helpers.ts' // 10-04 三端性能审计:后台入口把 Element Plus 整包注册进 app // (旧 main.ts: `app.use(ElementPlus)` + `element-plus/dist/index.css`) // 实测入口产物 index-*.js 1,129,621 B(gzip 374,350 B) / index-*.css 383,458 B(gzip 52,413 B), // 而 src 里只用到 29 个 `el-*` 标签 —— 每个后台页面的首屏都在扛整份组件库。 // // 改法:src/plugins/element.ts 里逐个 import 组件 + 按组件引样式 // (element-plus/es/components/<短名>/style/css 自带 base 与依赖组件样式)。 // // 这里的护栏不是装饰:按需引入最坏的结果是"某个页面某个组件没样式/没注册", // 而它不会让构建变红、只会让线上某个按钮变成裸 HTML。所以必须 // ① 从源码把用到的 `el-*` 标签推出来(不是手写清单),② 双向对齐注册表与样式导入, // ③ 名字对不上 EP 目录时立刻红(而不是静默漏引)。 /** 递归列出 src 下所有 .vue 文件(相对工程根)。 */ function vueFiles(dir = 'src'): string[] { const abs = join(process.cwd(), dir) const out: string[] = [] for (const name of readdirSync(abs)) { const rel = `${dir}/${name}` if (statSync(join(process.cwd(), rel)).isDirectory()) out.push(...vueFiles(rel)) else if (name.endsWith('.vue')) out.push(rel) } return out } /** 模板里用到的所有 `el-xxx-yyy` 标签(EP 目录名 = 去掉 el- 前缀,已逐个核过)。 */ function usedTags(): string[] { const tags = new Set() for (const file of vueFiles()) { for (const match of readSource(file).matchAll(/ part.charAt(0).toUpperCase() + part.slice(1)).join('') } /** * 逐个对注册数组里的条目调 `install(假 app)`,收集真正注册出来的组件名。 * * 为什么不能只比对数组文本:Element Plus 里子组件是 `withNoopInstall` 造的 * (`component.install = NOOP`),`app.use(ElRadioGroup)` 等于什么都没注册;只有父组件 * 的 `withInstall(main, extra)` 会把 main + extra 一起 `app.component(comp.name, comp)` 注册。 * 所以「数组里写着 ElRadioGroup / ElRadioButton」和「模板能解析出 el-radio-group」是两件事 —— * 前者当时全绿,后者在 10-05 的「编辑用户 → 角色」上渲染成了裸标签。 * 尺子必须是运行期注册出来的名字集合,不是清单字符串。 */ async function installedComponentNames(names: string[]): Promise> { const EP = (await import('element-plus')) as unknown as Record< string, { install?: (app: unknown) => void } | undefined > const out = new Map() for (const name of names) { const comp = EP[name] assert.ok(comp, `element-plus 没有导出 ${name}`) assert.equal(typeof comp?.install, 'function', `${name} 没有 install(),app.use 它是空转`) const registered: string[] = [] const app: Record = { component(n: string) { registered.push(n) return app }, directive() { return app }, config: { globalProperties: {} }, } comp!.install!(app) out.set(name, registered) } return out } // 命令式 API 与指令:没有对应模板标签,所以不算"注册表里的死条目" const EXTRA_REGISTERED = ['ElConfigProvider', 'ElMessage', 'ElMessageBox', 'ElLoading', 'ElLoadingDirective'] /** 剥掉注释后剩下的才是真会执行的代码:doc 里写着「不要再用 dist/index.css」不能算违规。 */ function codeOnly(source: string): string { return source .replace(//g, '') .replace(/\/\*[\s\S]*?\*\//g, '') .split('\n') .filter((line) => !line.trim().startsWith('//')) .join('\n') } /** src 下所有 .vue/.ts 源码(相对工程根)。 */ function srcCodeFiles(dir = 'src'): string[] { const abs = join(process.cwd(), dir) const out: string[] = [] for (const name of readdirSync(abs)) { const rel = `${dir}/${name}` if (statSync(join(process.cwd(), rel)).isDirectory()) out.push(...srcCodeFiles(rel)) else if (/\.(vue|ts)$/.test(name)) out.push(rel) } return out.sort() } // 整包入口的五种写法。少盯一种,首屏体积就静默退回原点。 const FULL_BUNDLE_PATTERNS: Array<[RegExp, string]> = [ [/['"]element-plus\/dist\/index\.css['"]/, '整包样式 element-plus/dist/index.css'], [/['"]element-plus\/theme-chalk\/index\.css['"]/, '整包样式 element-plus/theme-chalk/index.css'], [/['"]element-plus\/lib\/style\/css['"]/, '整包样式 element-plus/lib/style/css'], [/import\s+ElementPlus\s+from\s+['"]element-plus['"]/, '整包组件导入 import ElementPlus'], [/\.\s*use\(\s*ElementPlus\s*[,)]/, '整包注册 use(ElementPlus)'], ] test('perf_ep_no_full_bundle_entry_anywhere_in_src', () => { // 补一条 main.ts 那条锚点盖不到的面:按需引入之后最常见的倒退姿势, // 是某人碰到某个组件没样式时,在随便哪个页面里图省事引一句整包 CSS —— // main.ts 一个字没改,护栏照样绿,而产物体积已经回到 383,458 B。 const offenders: string[] = [] for (const file of srcCodeFiles()) { const code = codeOnly(readSource(file)) for (const [pattern, label] of FULL_BUNDLE_PATTERNS) { if (pattern.test(code)) offenders.push(`${file}: ${label}`) } } assert.deepEqual(offenders, [], 'src 里任何文件都不得再引 Element Plus 整包入口') }) test('perf_ep_no_full_bundle_registration_in_main', () => { const main = readSource('src/main.ts') assert.doesNotMatch(main, /app\.use\(ElementPlus/, 'main.ts 不得再整包 use(ElementPlus)') assert.doesNotMatch(main, /import\s+ElementPlus\s+from\s+['"]element-plus['"]/, '不得整包 import ElementPlus') assert.doesNotMatch(main, /element-plus\/dist\/index\.css/, '不得整包引 dist/index.css') }) /** 取 `const components = [...]` 里真正登记的组件名(剥掉注释行,防"注释也算注册"的假绿)。 */ function registeredComponents(registry: string): string[] { const start = registry.indexOf('const components = [') assert.notEqual(start, -1, '注册表里找不到 const components 数组') const body = registry.slice(start + 'const components = ['.length) const list = body.slice(0, body.indexOf(']')) return list .split('\n') .filter((line) => !line.trim().startsWith('//')) .map((line) => line.trim().replace(/,$/, '')) .filter((name) => /^El[A-Z]/.test(name)) } /** 命令式 API 的导入名(同样剥注释),用于注册完整性检查。 */ function importedNames(registry: string): string[] { return registry .split('\n') .filter((line) => !line.trim().startsWith('//')) .flatMap((line) => [...line.matchAll(/\b(El[A-Z][A-Za-z0-9]*)\b/g)].map((m) => m[1])) } test('perf_ep_registry_covers_every_used_tag', async () => { const registry = readSource('src/plugins/element.ts') const closure = await installedComponentNames(registeredComponents(registry)) const effective = new Set([...closure.values()].flat()) const missing = usedTags().map(toComponentName).filter((name) => !effective.has(name)) assert.deepEqual(missing, [], '有模板在用的 el-* 组件在 app.use 之后并未注册出来(页面会渲染成裸标签)') }) test('perf_ep_every_used_tag_imports_its_style', () => { const registry = readSource('src/plugins/element.ts') // 只看真的会执行到的行:注释掉的样式导入等于没引 const activeLines = registry .split('\n') .filter((line) => !line.trim().startsWith('//')) .join('\n') const missing = usedTags().filter((kebab) => !activeLines.includes(`element-plus/es/components/${kebab}/style/css`)) assert.deepEqual(missing, [], '有在用的 el-* 组件没引按组件样式(构建照样绿,页面会没样式)') }) test('perf_ep_registry_has_no_dead_entries', async () => { const registry = readSource('src/plugins/element.ts') const tags = usedTags() const used = new Set(tags) const usedComponentNames = new Set(tags.map(toComponentName)) const closure = await installedComponentNames(registeredComponents(registry)) const dead: string[] = [] for (const name of closure.keys()) { if (EXTRA_REGISTERED.includes(name)) continue const kebab = name.slice(2).replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase() if (used.has(kebab)) continue // 父组件例外:它自己不出现在模板里,但只有 app.use(它) 才把在用的子组件注册出来。 if ((closure.get(name) ?? []).some((n) => usedComponentNames.has(n))) continue dead.push(name) } assert.deepEqual([...new Set(dead)], [], '注册数组里留着没人用的组件(整包的问题不该在按需里重犯)') }) test('perf_ep_imperative_apis_keep_their_styles', () => { // 命令式弹层不在模板里,护栏的标签推导盖不到它们 —— 单独钉住 const registry = readSource('src/plugins/element.ts') const activeLines = registry.split('\n').filter((line) => !line.trim().startsWith('//')).join('\n') for (const name of ['ElMessage', 'ElMessageBox', 'ElLoadingDirective']) { assert.ok(importedNames(registry).includes(name), `${name} 必须显式导入`) } for (const style of ['message/style/css', 'message-box/style/css', 'loading/style/css']) { assert.ok(activeLines.includes(`element-plus/es/components/${style}`), `${style} 样式必须引`) } }) test('perf_ep_locale_still_applied_after_drop_plugin', () => { // 摘掉 use(ElementPlus, { locale }) 后,中文语言包只能靠 el-config-provider 提供; // 这条与 align-locale.test.ts 是同一不变式,换了通道不能丢。 const app = readSource('src/App.vue') assert.match(app, /]*:locale="zhCn"/, 'App.vue 需用 el-config-provider 提供 locale') assert.match(app, /element-plus\/es\/locale\/lang\/zh-cn/, '语言包必须来自 element-plus 官方路径') })