From 6dc942c888b57be0362a7283bf752c59a48d0670 Mon Sep 17 00:00:00 2001 From: wing <52194736+wingjie@users.noreply.github.com> Date: Wed, 2 Sep 2026 11:12:47 +0800 Subject: [PATCH] =?UTF-8?q?fix(demo-preview):=20=E4=BD=BF=E7=94=A8?= =?UTF-8?q?=E5=BC=82=E6=AD=A5=E7=BB=84=E4=BB=B6=E5=8A=A0=E8=BD=BD=E9=81=BF?= =?UTF-8?q?=E5=85=8D=20SSR=20=E6=8A=A5=E9=94=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 通过 defineAsyncComponent 动态导入,避免 demo 组件在服务端渲染时执行顶层副作用,解决 组件依赖 包初始化全局单例报错问题。 --- docs/.vitepress/config/plugins/demo-preview.ts | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/docs/.vitepress/config/plugins/demo-preview.ts b/docs/.vitepress/config/plugins/demo-preview.ts index 84f9c9b5d..8268b0d65 100644 --- a/docs/.vitepress/config/plugins/demo-preview.ts +++ b/docs/.vitepress/config/plugins/demo-preview.ts @@ -72,9 +72,16 @@ export const demoPreviewPlugin = (md: MarkdownRenderer) => { const uniqueWord = generateContentHash(componentDir); const ComponentName = `DemoComponent_${uniqueWord}`; - insertComponentImport( - `import ${ComponentName} from '${componentDir}/index.vue'`, - ); + // 使用异步组件加载 demo,避免 SSR 阶段执行 demo 模块的顶层副作用 + let asyncImport = `const ${ComponentName} = defineAsyncComponent(() => import('${componentDir}/index.vue'))`; + const currentContent = state.tokens + .map((token) => token.content) + .join(''); + if (!/import\s*\{[^}]*defineAsyncComponent[^}]*\}\s*from\s*['"]vue['"]/.test(currentContent)) { + asyncImport = `import { defineAsyncComponent } from 'vue';\n${asyncImport}`; + } + insertComponentImport(asyncImport); + const { path: _path } = state.env as MarkdownEnv; const index = state.tokens.findIndex((i) => i.content.match(regex));