Files
crawler-plugin/admin-frontend-vue/tests/perf-element-on-demand.test.ts
T
huangzd1997 85cbd56cd8 perf(后台首屏): Element Plus 改按需注册,入口 JS 1,129,783→737,303 B
同一棵树只翻 main.ts/App.vue 做 A/B(其余文件两轮一致,差值可整份归给这条):
入口 JS −34.7%、CSS −45.6%、dist 整树 −567,203 B;A 组跑两次字节与哈希完全相同。

新增 src/plugins/element.ts 显式注册表。没走用户端那套 ElementPlusResolver:
自动引入会把"到底注册了哪些组件"藏进产物,而按需注册的失败模式恰恰是
"漏一个组件不报错、页面渲染成裸标签",只有显式清单才能让护栏从源码推标签
做双向比对。语言包随之换到 App.vue 的 el-config-provider。

顺带摘掉两处重复请求:去重页 reAnalyze 白拉又丢返回值的那次整集 console、
看板 30s 心跳里无条件重拉的店铺候选(后端 SELECT DISTINCT 无缓存的字典数据)。

护栏 10 例(标签清单由 .vue 源码推导,不是手写名单)+ 变异自证 9/9 全杀;
前端全量 node --test 1698 例 0 红。只欠逐页浏览器视觉验证 —— 按需引入最坏的
那类回归不会让构建变红。
2026-10-04 18:38:14 +08:00

173 lines
8.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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<string>()
for (const file of vueFiles()) {
for (const match of readSource(file).matchAll(/<el-([a-z0-9]+(?:-[a-z0-9]+)*)/g)) {
tags.add(match[1])
}
}
return [...tags].sort()
}
/** 短名 → PascalCase 组件名(table-column → ElTableColumn)。 */
function toComponentName(kebab: string): string {
return 'El' + kebab.split('-').map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join('')
}
// 命令式 API 与指令:没有对应模板标签,所以不算"注册表里的死条目"
const EXTRA_REGISTERED = ['ElConfigProvider', 'ElMessage', 'ElMessageBox', 'ElLoading', 'ElLoadingDirective']
/** 剥掉注释后剩下的才是真会执行的代码:doc 里写着「不要再用 dist/index.css」不能算违规。 */
function codeOnly(source: string): string {
return source
.replace(/<!--[\s\S]*?-->/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', () => {
const registry = readSource('src/plugins/element.ts')
const registered = new Set(registeredComponents(registry))
const missing = usedTags().map(toComponentName).filter((name) => !registered.has(name))
assert.deepEqual(missing, [], '有模板在用的 el-* 组件没进注册数组(页面会渲染成裸标签)')
})
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', () => {
const registry = readSource('src/plugins/element.ts')
const used = new Set(usedTags())
const dead: string[] = []
for (const name of registeredComponents(registry)) {
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)) 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, /<el-config-provider\b[^>]*:locale="zhCn"/, 'App.vue 需用 el-config-provider 提供 locale')
assert.match(app, /element-plus\/es\/locale\/lang\/zh-cn/, '语言包必须来自 element-plus 官方路径')
})