avoid component reload on hmr due to pageData export

pull/1/head
Evan You 5 years ago
parent b4941bd730
commit 7bdde43f11

@ -51,13 +51,15 @@ export function createApp() {
if (inBrowser) {
// in browser: native dynamic import
return import(pagePath).then((page) => {
pageDataRef.value = readonly(page.__pageData)
if (page.__pageData) {
pageDataRef.value = readonly(JSON.parse(page.__pageData))
}
return page.default
})
} else {
// SSR, sync require
const page = require(pagePath)
pageDataRef.value = page.__pageData
pageDataRef.value = JSON.parse(page.__pageData)
return page.default
}
}, NotFound)

@ -19,7 +19,12 @@ export function createMarkdownToVueRenderFn(
) {
const md = createMarkdownRenderer(options)
return (src: string, file: string, lastUpdated: number) => {
return (
src: string,
file: string,
lastUpdated: number,
injectData = true
) => {
file = path.relative(root, file)
const cached = cache.get(src)
if (cached) {
@ -41,10 +46,9 @@ export function createMarkdownToVueRenderFn(
lastUpdated
}
const additionalBlocks = injectPageData(
data.hoistedTags || [],
pageData
)
const additionalBlocks = injectData
? injectPageData(data.hoistedTags || [], pageData)
: data.hoistedTags || []
// double wrapping since tempalte root node is never hoisted or turned into
// a static node.
@ -61,11 +65,10 @@ export function createMarkdownToVueRenderFn(
const scriptRE = /<\/script>/
function injectPageData(
tags: string[],
data: PageData
) {
const code = `\nexport const __pageData = ${JSON.stringify(data)}`
function injectPageData(tags: string[], data: PageData) {
const code = `\nexport const __pageData = ${JSON.stringify(
JSON.stringify(data)
)}`
const existingScriptIndex = tags.findIndex((tag) => scriptRE.test(tag))
if (existingScriptIndex > -1) {
tags[existingScriptIndex] = tags[existingScriptIndex].replace(

@ -5,11 +5,7 @@ import {
Plugin,
ServerConfig
} from 'vite'
import {
resolveConfig,
SiteConfig,
resolveSiteData
} from './config'
import { resolveConfig, SiteConfig, resolveSiteData } from './config'
import { createMarkdownToVueRenderFn } from './markdownToVue'
import { APP_PATH, SITE_DATA_REQUEST_PATH } from './utils/pathResolver'
@ -43,7 +39,16 @@ function createVitePressPlugin(config: SiteConfig): Plugin {
debugHmr(`reloading ${file}`)
const content = await cachedRead(null, file)
const timestamp = Date.now()
const { pageData, vueSrc } = markdownToVue(content, file, timestamp)
const { pageData, vueSrc } = markdownToVue(
content,
file,
timestamp,
// do not inject pageData on HMR
// it leads to vite to think <script> has changed and reloads the
// component instead of re-rendering.
// pageData needs separate HMR logic anyway (see below)
false
)
// notify the client to update page data
watcher.send({

Loading…
Cancel
Save