From b3f4711d20cea6bdac12e9205c8eeff7030787ea Mon Sep 17 00:00:00 2001 From: zhanjunhao <642307404@qq.com> Date: Fri, 20 Nov 2026 15:03:30 +0800 Subject: [PATCH] =?UTF-8?q?perf(build):=20=E4=BC=98=E5=8C=96=E5=BC=80?= =?UTF-8?q?=E5=8F=91=E9=A2=84=E7=83=AD=E4=B8=8E=E9=A6=96=E5=B1=8F=E5=88=86?= =?UTF-8?q?=E5=8C=85=E6=87=92=E5=8A=A0=E8=BD=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 减少应用启动时的静态依赖,增加首屏体积预算与懒加载边界校验。验证通过:875 项单测、UI 依赖审计、ESLint、Prettier、生产构建与首屏产物校验;Chrome 模拟回归通过。 --- README.md | 4 + docs/CHANGELOG.md | 8 ++ scripts/verify-build.mjs | 88 ++++++++++++++++++++-- src/App.jsx | 7 +- src/components/auth/LazyAgreementModal.jsx | 15 ++++ src/components/auth/LoginForm.jsx | 2 +- src/components/auth/RegisterForm.jsx | 2 +- src/components/layout/PageLayout.jsx | 10 +-- src/components/layout/headerbar/index.jsx | 30 +++++--- src/components/ui/index.jsx | 2 +- src/hooks/common/useOrgMembership.js | 2 +- src/index.jsx | 2 +- src/pages/Home/index.jsx | 7 +- vite.config.js | 15 +++- 14 files changed, 161 insertions(+), 33 deletions(-) create mode 100644 src/components/auth/LazyAgreementModal.jsx diff --git a/README.md b/README.md index e867c760..495f8908 100644 --- a/README.md +++ b/README.md @@ -143,6 +143,7 @@ monkey-ai-web/ | --- | --- | | `npm run dev` | 启动开发服务 | | `npm run build` | 生产构建,输出 `dist/` | +| `npm run verify:build -- <产物目录> --startup` | 校验静态入口、首屏 JS gzip 预算和按需加载边界;产物须用 `--manifest` 生成 | | `npm run preview` | 本地预览构建结果(默认端口 4173) | | `npm test -- --test-concurrency=1` | 串行运行单测(扫描 `src/`、`tests/`、`test/unit/`;新增共享单测放 `test/unit/`) | | `npm run eslint` / `npm run eslint:fix` | ESLint 检查(零警告门禁)/ 自动修复 | @@ -191,6 +192,9 @@ Trace、失败截图、CI JUnit 在 `test-results//`,HTML 在 `playwrig ## 7. 构建与部署 +- **首屏分包**:React 运行时独立缓存,公告和协议预览保留在按需 chunk;首页仅在收到非空 Markdown 时下载解析器。首屏启动 JS 预算为 820 KiB gzip,不含路由按需包和 CSS;验收构建使用 `npm run build -- --manifest --outDir <临时目录>`,再执行 `npm run verify:build -- <临时目录> --startup`。 +- **开发预热**:只预热应用入口、布局和路由,不预热所有页面或禁用依赖发现。没有全量 `vendor` 分组,也没有将图表、文档等浏览器依赖外置。 + ```bash npm ci npm run build diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 1565be17..9706ffde 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -10,6 +10,14 @@ ## 2026-11-20 +### 性能 · 开发预热与公共首屏分包 + +- **范围**:Vite 开发和生产配置、应用启动、首页和认证页的加载边界。 +- **变更**:预热入口、布局和路由;启动路径直接导入所需模块,拆出可单独缓存的 React 运行时;公告、协议预览和首页 Markdown 解析按需加载。 +- **影响**:减少默认首页和认证页首屏 JS,不改变接口、权限、设置与登录流程;支持基于构建清单验收启动预算及懒加载边界。 +- **回滚**:仅逆向恢复本条对应的配置、显式导入、懒加载与产物校验差异。 +- **关联**:`vite.config.js`、`src/index.jsx`、`src/components/auth/LazyAgreementModal.jsx`、`scripts/verify-build.mjs`。 + ### 修复 · 旧 UI 库审计规则统一 - **范围**:ESLint、UI 依赖审计、回归单测与开发文档。 diff --git a/scripts/verify-build.mjs b/scripts/verify-build.mjs index d09aee6c..e1520eb2 100644 --- a/scripts/verify-build.mjs +++ b/scripts/verify-build.mjs @@ -1,8 +1,77 @@ import { readFile, access } from 'node:fs/promises'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; +import { gzipSync } from 'node:zlib'; -export async function verifyBuild(directory) { +const BOOTSTRAP_GZIP_LIMIT = 820 * 1024; +const NOTICE = 'src/components/layout/NoticeModal.jsx'; +const AGREEMENT = 'src/components/common/DocumentRenderer/AgreementModal.jsx'; +const HEADER = 'src/components/layout/headerbar/index.jsx'; +const HOME = 'src/pages/Home/index.jsx'; +const MARKED = 'node_modules/marked/lib/marked.esm.js'; + +function resolveAsset(root, asset) { + const filename = path.resolve(root, asset.replace(/^\//, '')); + if (!filename.startsWith(root + path.sep)) + throw new Error(`Build asset escapes output directory: ${asset}`); + return filename; +} + +function staticChunks(manifest, roots) { + const seen = new Set(); + const visit = (key) => { + if (seen.has(key)) return; + const chunk = manifest[key]; + if (!chunk) throw new Error(`Missing build manifest chunk: ${key}`); + seen.add(key); + for (const dependency of chunk.imports || []) visit(dependency); + }; + roots.forEach(visit); + return seen; +} + +async function verifyStartup(root) { + const manifest = JSON.parse( + await readFile(path.join(root, '.vite', 'manifest.json'), 'utf8'), + ); + const entry = 'index.html'; + for (const [routes, deferred] of [ + [ + [entry, HOME, HEADER], + [NOTICE, MARKED], + ], + [ + [entry, 'src/components/auth/LoginForm.jsx', HEADER], + [AGREEMENT, NOTICE], + ], + [ + [entry, 'src/components/auth/RegisterForm.jsx', HEADER], + [AGREEMENT, NOTICE], + ], + ]) { + const eager = staticChunks(manifest, routes); + for (const feature of deferred) { + if (!manifest[feature]?.isDynamicEntry || eager.has(feature)) + throw new Error(`Expected an independent lazy chunk: ${feature}`); + } + } + + const files = new Set( + [...staticChunks(manifest, [entry])].map((key) => manifest[key].file), + ); + let bootstrapGzipBytes = 0; + for (const file of files) { + const source = await readFile(resolveAsset(root, file)); + bootstrapGzipBytes += gzipSync(source).length; + } + if (bootstrapGzipBytes > BOOTSTRAP_GZIP_LIMIT) + throw new Error( + `Bootstrap JS exceeds 820 KiB gzip: ${bootstrapGzipBytes} B`, + ); + return { bootstrapGzipBytes, bootstrapChunks: files.size }; +} + +export async function verifyBuild(directory, { startup = false } = {}) { const root = path.resolve(directory); const html = await readFile(path.join(root, 'index.html'), 'utf8'); // Inspect actual resource tags, not URLs embedded in comments or inline scripts. @@ -21,17 +90,22 @@ export async function verifyBuild(directory) { if (!assets.some((value) => /\.js$/.test(value))) throw new Error('Build has no JavaScript entry'); for (const asset of assets) { - const filename = path.resolve(root, asset.replace(/^\//, '')); - if (!filename.startsWith(root + path.sep)) - throw new Error(`Build asset escapes output directory: ${asset}`); - await access(filename); + await access(resolveAsset(root, asset)); } - return { root, assets: assets.length }; + return { + root, + assets: assets.length, + ...(startup ? await verifyStartup(root) : {}), + }; } if ( process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url) ) { - console.log(await verifyBuild(process.argv[2] || 'dist')); + const args = process.argv.slice(2); + const directory = args.find((argument) => argument !== '--startup') || 'dist'; + console.log( + await verifyBuild(directory, { startup: args.includes('--startup') }), + ); } diff --git a/src/App.jsx b/src/App.jsx index 4bbfdb9c..a6b8068d 100644 --- a/src/App.jsx +++ b/src/App.jsx @@ -5,7 +5,12 @@ import { isMiniProgramWebView, } from './helpers/miniProgram'; import Loading from './components/common/ui/Loading'; -import { AuthRedirect, PrivateRoute, AdminRoute, RootRoute } from './helpers'; +import { + AuthRedirect, + PrivateRoute, + AdminRoute, + RootRoute, +} from './helpers/auth'; import NotFound from './pages/NotFound'; import Forbidden from './pages/Forbidden'; import { StatusContext } from './context/Status'; diff --git a/src/components/auth/LazyAgreementModal.jsx b/src/components/auth/LazyAgreementModal.jsx new file mode 100644 index 00000000..39868897 --- /dev/null +++ b/src/components/auth/LazyAgreementModal.jsx @@ -0,0 +1,15 @@ +import React, { lazy, Suspense } from 'react'; + +const AgreementModal = lazy( + () => import('../common/DocumentRenderer/AgreementModal'), +); + +export default function LazyAgreementModal(props) { + if (!props.type) return null; + + return ( + + + + ); +} diff --git a/src/components/auth/LoginForm.jsx b/src/components/auth/LoginForm.jsx index a49180d6..23dd9329 100644 --- a/src/components/auth/LoginForm.jsx +++ b/src/components/auth/LoginForm.jsx @@ -53,7 +53,7 @@ import GlassCard from './GlassCard'; import AuthCardHeader from './AuthCardHeader'; import AuthLoginTabs from './AuthLoginTabs'; import AuthDivider from './AuthDivider'; -import AgreementModal from '../common/DocumentRenderer/AgreementModal'; +import AgreementModal from './LazyAgreementModal'; import { isMiniProgramWebView, withMiniProgramLogins, diff --git a/src/components/auth/RegisterForm.jsx b/src/components/auth/RegisterForm.jsx index c091663c..c82728dd 100644 --- a/src/components/auth/RegisterForm.jsx +++ b/src/components/auth/RegisterForm.jsx @@ -48,7 +48,7 @@ import AuthCardHeader from './AuthCardHeader'; import AuthLoginTabs from './AuthLoginTabs'; import AuthDivider from './AuthDivider'; import { Shield, Smartphone, QrCode } from 'lucide-react'; -import AgreementModal from '../common/DocumentRenderer/AgreementModal'; +import AgreementModal from './LazyAgreementModal'; import { isMiniProgramWebView, withMiniProgramLogins, diff --git a/src/components/layout/PageLayout.jsx b/src/components/layout/PageLayout.jsx index bcb0c92c..0a80ef3c 100644 --- a/src/components/layout/PageLayout.jsx +++ b/src/components/layout/PageLayout.jsx @@ -11,17 +11,15 @@ import React, { } from 'react'; import { useIsMobile } from '../../hooks/common/useIsMobile'; import { useTranslation } from 'react-i18next'; +import { API } from '../../helpers/api'; +import { isAuthPagePath } from '../../helpers/auth'; import { - API, clearUserData, getUserData, - getLogo, - getSystemName, - isAuthPagePath, - showError, setStatusData, setUserData, -} from '../../helpers'; +} from '../../helpers/data'; +import { getLogo, getSystemName, showError } from '../../helpers/utils'; import { UserContext } from '../../context/User'; import { StatusContext } from '../../context/Status'; import { useLocation } from 'react-router-dom'; diff --git a/src/components/layout/headerbar/index.jsx b/src/components/layout/headerbar/index.jsx index 10df1c78..13d7b0c0 100644 --- a/src/components/layout/headerbar/index.jsx +++ b/src/components/layout/headerbar/index.jsx @@ -1,17 +1,18 @@ -import React from 'react'; +import React, { lazy, Suspense, useEffect, useState } from 'react'; import { useLocation } from 'react-router-dom'; -import { isAuthPagePath } from '../../../helpers'; +import { isAuthPagePath } from '../../../helpers/auth'; import { useHeaderBar } from '../../../hooks/common/useHeaderBar'; import { useNotifications } from '../../../hooks/common/useNotifications'; import { useNavigation } from '../../../hooks/common/useNavigation'; import { usePartnerWorkspaceEntry } from '../../../hooks/common/usePartnerWorkspaceEntry'; -import NoticeModal from '../NoticeModal'; import MobileMenuButton from './MobileMenuButton'; import HeaderLogo from './HeaderLogo'; import Navigation from './Navigation'; import MobileNavMenu from './MobileNavMenu'; import ActionButtons from './ActionButtons'; +const NoticeModal = lazy(() => import('../NoticeModal')); + const HeaderBar = ({ onMobileMenuToggle, drawerOpen }) => { const location = useLocation(); // 认证页(登录/注册/企业登录等)顶栏按行业惯例最小化: @@ -69,6 +70,11 @@ const HeaderBar = ({ onMobileMenuToggle, drawerOpen }) => { (link) => link.itemKey !== 'keyManagement', ); + const [hasOpenedNotice, setHasOpenedNotice] = useState(false); + useEffect(() => { + if (noticeVisible) setHasOpenedNotice(true); + }, [noticeVisible]); + return (
{/* ===== BACKGROUND LAYERS ===== */} @@ -94,13 +100,17 @@ const HeaderBar = ({ onMobileMenuToggle, drawerOpen }) => { /> {/* ===== CONTENT ===== */} - 0 ? 'system' : 'inApp'} - unreadKeys={getUnreadKeys()} - /> + {(noticeVisible || hasOpenedNotice) && ( + + 0 ? 'system' : 'inApp'} + unreadKeys={getUnreadKeys()} + /> + + )}
{/* 高度断点必须用 md(768) 而非 sm(640):PageLayout 的 headerBarHeight 按 diff --git a/src/components/ui/index.jsx b/src/components/ui/index.jsx index 1a6d06ab..ca63a0dc 100644 --- a/src/components/ui/index.jsx +++ b/src/components/ui/index.jsx @@ -1,5 +1,6 @@ import React, { forwardRef } from 'react'; import * as Ant from 'antd'; +export { Checkbox, Col, Grid, List, Slider } from 'antd'; import { controlSize, placement } from './controls'; import { centerPaginationEvents, @@ -25,7 +26,6 @@ import { export * from './controls'; export { Form, withField } from './form'; export { Chat } from './chat'; -export const { Checkbox, Col, Grid, List, Slider } = Ant; export const Layout = Object.assign( forwardRef(function Layout({ style, hasSider, ...props }, ref) { return ( diff --git a/src/hooks/common/useOrgMembership.js b/src/hooks/common/useOrgMembership.js index e1a8f69b..45b39443 100644 --- a/src/hooks/common/useOrgMembership.js +++ b/src/hooks/common/useOrgMembership.js @@ -1,5 +1,5 @@ import { useState, useEffect } from 'react'; -import { API } from '../../helpers'; +import { API } from '../../helpers/api'; const ADMIN_ROLES = ['owner', 'admin', 'super_admin']; diff --git a/src/index.jsx b/src/index.jsx index 216bfd6c..fe1b52a6 100644 --- a/src/index.jsx +++ b/src/index.jsx @@ -7,7 +7,7 @@ import { ThemeProvider } from './context/Theme'; import PageLayout from './components/layout/PageLayout'; import i18n, { loadLanguage } from './i18n/i18n'; import { bootstrapLanguage, createBrowserEnv } from './i18n/bootstrap'; -import { API } from './helpers'; +import { API } from './helpers/api'; import './styles/tokens.css'; import './index.css'; import './styles/action-icons.css'; diff --git a/src/pages/Home/index.jsx b/src/pages/Home/index.jsx index 50db8879..7c03f5d0 100644 --- a/src/pages/Home/index.jsx +++ b/src/pages/Home/index.jsx @@ -20,10 +20,10 @@ import React, { useCallback, } from 'react'; import { Button } from '@/components/ui'; -import { API, showError } from '../../helpers'; +import { API } from '../../helpers/api'; +import { showError } from '../../helpers/utils'; import { StatusContext } from '../../context/Status'; import { useActualTheme } from '../../context/Theme'; -import { marked } from 'marked'; import { useTranslation } from 'react-i18next'; import { Link, useNavigate } from 'react-router-dom'; import { @@ -80,7 +80,8 @@ const Home = () => { const { success, message, data } = res.data; if (success) { let content = data; - if (!isUrl(data)) { + if (data !== '' && !isUrl(data)) { + const { marked } = await import('marked'); content = marked.parse(data); } setHomePageContent(content); diff --git a/vite.config.js b/vite.config.js index 514d342b..153aebec 100644 --- a/vite.config.js +++ b/vite.config.js @@ -15,6 +15,7 @@ const DEV_PROXY_TARGET = 'http://134.175.227.134:13000'; * 这是既有行为,保持不变;若要收紧为「只匹配项目 src 目录」,属于独立变更。 */ const JSX_IN_JS_RE = /src\/.*\.js$/; +const REACT_RUNTIME_RE = /\/node_modules\/(?:react|react-dom|scheduler)\//; /** * 让 JSX_IN_JS_RE 命中的 .js 按 JSX 语法解析。 @@ -25,7 +26,7 @@ function jsxInJsPlugin() { return { name: 'treat-js-files-as-jsx', async transform(code, id) { - if (!JSX_IN_JS_RE.test(id)) { + if (!JSX_IN_JS_RE.test(id) || !code.includes('<')) { return null; } @@ -131,8 +132,13 @@ export default defineConfig(({ mode, command }) => { target: 'es2015', // 生产环境不需要 sourcemap sourcemap: false, + reportCompressedSize: false, rollupOptions: { output: { + onlyExplicitManualChunks: true, + manualChunks(id) { + if (REACT_RUNTIME_RE.test(id)) return 'react-runtime'; + }, // 文件名带内容 hash,便于浏览器长期缓存与增量更新 chunkFileNames: 'assets/[name]-[hash].js', entryFileNames: 'assets/[name]-[hash].js', @@ -144,6 +150,13 @@ export default defineConfig(({ mode, command }) => { // 监听所有网卡,便于局域网与容器内访问 host: '0.0.0.0', port: '5174', + warmup: { + clientFiles: [ + './src/index.jsx', + './src/components/layout/PageLayout.jsx', + './src/App.jsx', + ], + }, // Browser reports contain HTML; watching them would reload active acceptance pages. watch: { ignored: [