From 6174362c53ef68cf460180ea62a7fe8d98ca115c Mon Sep 17 00:00:00 2001 From: meteorlxy Date: Tue, 14 Jun 2022 16:41:49 +0800 Subject: [PATCH] refactor: handle page data hmr in the same file (#779) --- src/client/app/index.ts | 22 ---------------------- src/client/app/router.ts | 23 ++++++++++++++++++++++- 2 files changed, 22 insertions(+), 23 deletions(-) diff --git a/src/client/app/index.ts b/src/client/app/index.ts index 05e16468..7fcfc53a 100644 --- a/src/client/app/index.ts +++ b/src/client/app/index.ts @@ -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() diff --git a/src/client/app/router.ts b/src/client/app/router.ts index 57398144..9dd424bd 100644 --- a/src/client/app/router.ts +++ b/src/client/app/router.ts @@ -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 +}