Browse Source
fix(demo-preview): 使用异步组件加载避免 SSR 报错
通过 defineAsyncComponent 动态导入,避免 demo 组件在服务端渲染时执行顶层副作用,解决 组件依赖 包初始化全局单例报错问题。
pull/8358/head
wing
4 weeks ago
committed by
GitHub
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with
10 additions and
3 deletions
-
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)); |
|
|
|
|