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 红。只欠逐页浏览器视觉验证 —— 按需引入最坏的
那类回归不会让构建变红。
This commit is contained in:
2026-10-04 18:38:14 +08:00
parent 1f23369629
commit 5111858346
8 changed files with 386 additions and 14 deletions
+6 -1
View File
@@ -1,7 +1,12 @@
<script setup lang="ts">
import { RouterView } from 'vue-router'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
</script>
<template>
<RouterView />
<!-- 摘掉整包 use(ElementPlus, { locale }) 后,全局配置只能走 config-provider:
日期控件(周/月/年份)、分页组件(上一页/下一页)靠它显示中文。 -->
<el-config-provider :locale="zhCn">
<RouterView />
</el-config-provider>
</template>
+8 -5
View File
@@ -1,11 +1,14 @@
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import ElementPlus from 'element-plus'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import 'element-plus/dist/index.css'
import { installElement } from '@/plugins/element'
import '@/styles/main.css'
import App from './App.vue'
import router from './router'
// 全局中文语言包:日期控件(周/月/年份)、分页组件(上一页/下一页)等均显示中文。
createApp(App).use(createPinia()).use(router).use(ElementPlus, { locale: zhCn }).mount('#app')
// Element Plus 改为按需注册(见 src/plugins/element.ts);全局中文语言包改由
// App.vue 的 <el-config-provider :locale="zhCn"> 提供,不要再在这里 use(ElementPlus)。
const app = createApp(App)
app.use(createPinia())
app.use(router)
installElement(app)
app.mount('#app')
@@ -139,11 +139,14 @@ async function loadVariants(silent = false) {
}
}
/** 汇总卡与店铺候选只描述客户端任务,两个页签都刷新它们(切页签时看到的就是最新)。 */
/** 汇总卡与店铺候选只描述客户端任务,两个页签都刷新它们(切页签时看到的就是最新)。
* 店铺候选是字典数据(后端 SELECT DISTINCT、无缓存),所以它不进 30s 心跳:
* 心跳每轮都重拉等于把一次全库去重乘以 2880/天。代价是新入库店铺要等
* 下一次进页/切页签/点「刷新」才会出现在下拉里。 */
async function refreshAll(silent = false) {
await Promise.all([
loadOverview(),
loadShopOptions(),
silent ? Promise.resolve() : loadShopOptions(),
activeTab.value === 'tasks' ? loadTasks(silent) : loadVariants(silent),
])
updatedAt.value = formatDateTime(Date.now())
@@ -274,7 +274,6 @@ function switchScope(next: Scope) {
async function reAnalyze() {
reanalyzing.value = true
try {
await fetchDuplicateConsole({ view: '', asin: '', shopName: '', group: '', country: '', site: '', dateFrom: '', dateTo: '' })
await loadConsole()
toast('重新分析完成,已同步最新扫描结果')
} catch (error) {
+131
View File
@@ -0,0 +1,131 @@
/**
* Element Plus 按需注册(替代旧的 `app.use(ElementPlus)` + `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-*` 标签。
*
* 两条不成文但会咬人的规矩,改这个文件前先读:
* 1. 新增/换用任何 `el-*` 标签,这里必须同时加「组件导入」和「按组件样式导入」。
* 少一条不会让构建变红,只会让那个页面渲染成裸标签 —— 护栏在
* tests/perf-element-on-demand.test.ts,它从源码推标签清单来比对这份文件。
* 2. 样式一律走 `element-plus/es/components/<短名>/style/css`,它会带上 base
* 与依赖组件的样式(例如 message-box 自带 input/button/overlay);
* 不要图省事改回 `theme-chalk/index.css` 或 `dist/index.css`。
*
* 语言包见 src/App.vue 的 `<el-config-provider :locale="zhCn">` —— 摘掉整包插件后
* 全局配置只能从 config-provider 走,别再指望 use(ElementPlus, { locale })。
*/
import type { App } from 'vue'
import {
ElAlert,
ElBreadcrumb,
ElBreadcrumbItem,
ElButton,
ElCheckbox,
ElConfigProvider,
ElDatePicker,
ElDescriptions,
ElDescriptionsItem,
ElDialog,
ElDrawer,
ElEmpty,
ElForm,
ElFormItem,
ElInput,
ElInputNumber,
ElLoadingDirective,
ElMenu,
ElMenuItem,
ElOption,
ElProgress,
ElRadioButton,
ElRadioGroup,
ElResult,
ElScrollbar,
ElSelect,
ElSubMenu,
ElTable,
ElTableColumn,
ElTree,
ElUpload,
} from 'element-plus'
// 模板在用的组件:样式按组件引(顺序与标签名字典序一致,方便和护栏清单对读)
import 'element-plus/es/components/alert/style/css'
import 'element-plus/es/components/breadcrumb/style/css'
import 'element-plus/es/components/breadcrumb-item/style/css'
import 'element-plus/es/components/button/style/css'
import 'element-plus/es/components/checkbox/style/css'
import 'element-plus/es/components/config-provider/style/css'
import 'element-plus/es/components/date-picker/style/css'
import 'element-plus/es/components/descriptions/style/css'
import 'element-plus/es/components/descriptions-item/style/css'
import 'element-plus/es/components/dialog/style/css'
import 'element-plus/es/components/drawer/style/css'
import 'element-plus/es/components/empty/style/css'
import 'element-plus/es/components/form/style/css'
import 'element-plus/es/components/form-item/style/css'
import 'element-plus/es/components/input/style/css'
import 'element-plus/es/components/input-number/style/css'
import 'element-plus/es/components/menu/style/css'
import 'element-plus/es/components/menu-item/style/css'
import 'element-plus/es/components/option/style/css'
import 'element-plus/es/components/progress/style/css'
import 'element-plus/es/components/radio-button/style/css'
import 'element-plus/es/components/radio-group/style/css'
import 'element-plus/es/components/result/style/css'
import 'element-plus/es/components/scrollbar/style/css'
import 'element-plus/es/components/select/style/css'
import 'element-plus/es/components/sub-menu/style/css'
import 'element-plus/es/components/table/style/css'
import 'element-plus/es/components/table-column/style/css'
import 'element-plus/es/components/tree/style/css'
import 'element-plus/es/components/upload/style/css'
// 命令式 API:不写在模板里,但同样要自带样式,否则弹层是裸 HTML
import { ElMessage, ElMessageBox } from 'element-plus'
import 'element-plus/es/components/message/style/css'
import 'element-plus/es/components/message-box/style/css'
// v-loading 指令与其服务样式
import 'element-plus/es/components/loading/style/css'
export { ElMessage, ElMessageBox }
const components = [
ElAlert,
ElBreadcrumb,
ElBreadcrumbItem,
ElButton,
ElCheckbox,
ElConfigProvider,
ElDatePicker,
ElDescriptions,
ElDescriptionsItem,
ElDialog,
ElDrawer,
ElEmpty,
ElForm,
ElFormItem,
ElInput,
ElInputNumber,
ElMenu,
ElMenuItem,
ElOption,
ElProgress,
ElRadioButton,
ElRadioGroup,
ElResult,
ElScrollbar,
ElSelect,
ElSubMenu,
ElTable,
ElTableColumn,
ElTree,
ElUpload,
]
export function installElement(app: App): void {
for (const component of components) app.use(component)
app.directive('loading', ElLoadingDirective)
}
@@ -7,15 +7,17 @@ import { readSource } from './helpers.ts'
// 不变式:应用入口为 Element Plus 注册 zh-cn 全局 locale(date-picker/pagination 全部跟随)。
test('align_locale_normal_primary_path', () => {
const main = readSource('src/main.ts')
assert.match(main, /zh-cn|zhCn/i, 'main.ts 应引入 element-plus 中文语言包')
assert.match(main, /locale\s*[:=]\s*zhCn|locale,\s*zhCn/, 'ElementPlus 注册需携带 locale 配置')
// 10-04 起 EP 改按需注册(src/plugins/element.ts),全局配置通道换成 el-config-provider,
// 所以这条不变式的落点从 main.ts 移到 App.vue —— 强度不许降:仍然要求真的引官方语言包并挂上 locale。
const app = readSource('src/App.vue')
assert.match(app, /zh-cn|zhCn/i, 'App.vue 应引入 element-plus 中文语言包')
assert.match(app, /<el-config-provider\b[^>]*:locale="zhCn"/, 'locale 必须经 el-config-provider 挂到全局')
})
test('align_locale_normal_variant_input', () => {
// 语言包必须来自 element-plus 官方路径(es/locale 或 dist/locale),不接受自造空对象。
const main = readSource('src/main.ts')
assert.match(main, /element-plus\/(es|dist)\/locale/, 'locale 导入需指向 element-plus 语言包')
const app = readSource('src/App.vue')
assert.match(app, /element-plus\/(es|dist)\/locale/, 'locale 导入需指向 element-plus 语言包')
})
test('align_locale_boundary_empty_input', () => {
@@ -0,0 +1,57 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { readSource, occurrences } from './helpers.ts'
// 10-04 三端性能审计(我逐行核过的两条重复请求):
// ① DuplicateCheckPage.reAnalyze() 先 await fetchDuplicateConsole(全空参数) 把返回值丢掉,
// 再 loadConsole() 拉一次 —— 服务端 console 端点纯读(loadLatest 按行号缓存,无"预热"必要),
// 所以那一次是白跑的整集查询。
// ② TaskCenterBoardPage.refreshAll() 的 Promise.all 里无条件带 loadShopOptions(),
// 而它是 30s 心跳(POLL_INTERVAL_MS)走的同一条函数 —— 店铺候选是字典数据
// (后端 SELECT DISTINCT 无缓存),进热路径等于每轮心跳多打一次全库去重。
// 两条都用「排他 + 精确锚」断言:既钉住修好的形状,也钉住"旧的无条件写法"不得回流。
/** 取顶层函数体(从签名后的第一个 { 到配对的 })。 */
function functionBody(source: string, signature: string): string {
const start = source.indexOf(signature)
assert.notEqual(start, -1, `源码里找不到 ${signature}`)
const open = source.indexOf('{', start + signature.length)
assert.notEqual(open, -1, `${signature} 后面没有函数体`)
let depth = 0
for (let i = open; i < source.length; i += 1) {
if (source[i] === '{') depth += 1
else if (source[i] === '}') {
depth -= 1
if (depth === 0) return source.slice(open + 1, i)
}
}
assert.fail(`${signature} 的函数体括号没闭合`)
}
test('perf_dup_reanalyze_does_not_fetch_console_twice', () => {
const page = readSource('src/pages/tasks/DuplicateCheckPage.vue')
const body = functionBody(page, 'async function reAnalyze(')
// 丢弃返回值的整集查询必须消失(修复前正是这一行让它翻倍)
assert.equal(occurrences(body, 'fetchDuplicateConsole('), 0,
'reAnalyze 不应自己再拉一次 duplicate-check-console')
assert.equal(occurrences(body, 'loadConsole('), 1,
'reAnalyze 只经 loadConsole() 拉一次')
})
test('perf_board_shop_options_stay_out_of_heartbeat', () => {
const board = readSource('src/pages/task-center/TaskCenterBoardPage.vue')
const body = functionBody(board, 'async function refreshAll(')
assert.ok(/silent\s*.*loadShopOptions/s.test(body.split('\n').filter((l) => /loadShopOptions/.test(l)).join('\n')),
'loadShopOptions 必须由 silent 分档,只在进页/手动刷新/切页签时重拉')
// 无条件那一行(修复前的形状)不得回流
assert.equal(occurrences(body, '\n loadShopOptions(),'), 0,
'refreshAll 里不得保留无条件的 loadShopOptions() 直列')
})
test('perf_board_heartbeat_is_the_silent_path', () => {
// 上一那条断言只有"心跳确实走 silent"才成立;这里钉住这个前提本身。
const board = readSource('src/pages/task-center/TaskCenterBoardPage.vue')
assert.match(board, /setInterval\([\s\S]{0,200}refreshAll\(true\)[\s\S]{0,200}POLL_INTERVAL_MS/,
'30s 心跳必须以 silent=true 调 refreshAll')
assert.match(board, /POLL_INTERVAL_MS = 30_000/, '心跳周期仍是 30s(改动没顺手调周期)')
})
@@ -0,0 +1,172 @@
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 官方路径')
})