refactor: handle page data hmr in the same file (#779)

pull/791/head
meteorlxy 2 years ago committed by GitHub
parent c5c3c64851
commit 6174362c53
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -15,7 +15,6 @@ import { usePrefetch } from './composables/preFetch'
import { dataSymbol, initData } from './data'
import { Content } from './components/Content'
import { ClientOnly } from './components/ClientOnly'
import { PageDataPayload } from '../shared'
const NotFound = Theme.NotFound || (() => '404 Not Found')
@ -46,8 +45,6 @@ const VitePressApp = {
export function createApp() {
const router = newRouter()
handleHMR(router)
const app = newApp()
app.provide(RouterSymbol, router)
@ -116,25 +113,6 @@ function newRouter(): Router {
}, NotFound)
}
function handleHMR(router: Router): void {
// update route.data on HMR updates of active page
if (import.meta.hot) {
// hot reload pageData
import.meta.hot!.on('vitepress:pageData', (payload: PageDataPayload) => {
if (shouldHotReload(payload)) {
router.route.data = payload.pageData
}
})
}
}
function shouldHotReload(payload: PageDataPayload): boolean {
const payloadPath = payload.path.replace(/(\bindex)?\.md$/, '')
const locationPath = location.pathname.replace(/(\bindex)?\.html$/, '')
return payloadPath === locationPath
}
if (inBrowser) {
const { app, router, data } = createApp()

@ -1,6 +1,7 @@
import { reactive, inject, markRaw, nextTick, readonly } from 'vue'
import type { Component, InjectionKey } from 'vue'
import { PageData, notFoundPageData } from '../shared'
import { notFoundPageData } from '../shared'
import type { PageData, PageDataPayload } from '../shared'
import { inBrowser, withBase } from './utils'
import { siteDataRef } from './data'
@ -173,6 +174,8 @@ export function createRouter(
})
}
handleHMR(route)
return {
route,
go
@ -230,3 +233,21 @@ function scrollTo(el: HTMLElement, hash: string, smooth = false) {
}
}
}
function handleHMR(route: Route): void {
// update route.data on HMR updates of active page
if (import.meta.hot) {
// hot reload pageData
import.meta.hot!.on('vitepress:pageData', (payload: PageDataPayload) => {
if (shouldHotReload(payload)) {
route.data = payload.pageData
}
})
}
}
function shouldHotReload(payload: PageDataPayload): boolean {
const payloadPath = payload.path.replace(/(\bindex)?\.md$/, '')
const locationPath = location.pathname.replace(/(\bindex)?\.html$/, '')
return payloadPath === locationPath
}

Loading…
Cancel
Save