From 48fae52d17fa27c42e0ae993e0ba4614dbc4385d Mon Sep 17 00:00:00 2001 From: meteorlxy Date: Thu, 16 Jun 2022 19:58:54 +0800 Subject: [PATCH] refactor: improve site data parsing (#780) --- src/client/app/data.ts | 13 +++++-------- src/client/shim.d.ts | 3 ++- src/node/plugin.ts | 4 +++- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/client/app/data.ts b/src/client/app/data.ts index fb68378f7aa4..3e3fa7a2be40 100644 --- a/src/client/app/data.ts +++ b/src/client/app/data.ts @@ -1,6 +1,6 @@ import { InjectionKey, Ref, shallowRef, readonly, computed, inject } from 'vue' import { Route } from './router' -import serializedSiteData from '@siteData' +import siteData from '@siteData' import { PageData, SiteData, @@ -25,17 +25,14 @@ export interface VitePressData { // site data is a singleton export type SiteDataRef = Ref> -export const siteDataRef: Ref = shallowRef(parse(serializedSiteData)) - -function parse(data: string): SiteData { - const parsed = JSON.parse(data) - return (import.meta.env.DEV ? readonly(parsed) : parsed) as SiteData -} +export const siteDataRef: Ref = shallowRef( + import.meta.env.PROD ? siteData : readonly(siteData) +) // hmr if (import.meta.hot) { import.meta.hot!.accept('/@siteData', (m) => { - siteDataRef.value = parse(m.default) + siteDataRef.value = m.default }) } diff --git a/src/client/shim.d.ts b/src/client/shim.d.ts index 868fc51efbf3..0c28b109962b 100644 --- a/src/client/shim.d.ts +++ b/src/client/shim.d.ts @@ -10,7 +10,8 @@ declare module '*.vue' { } declare module '@siteData' { - const data: string + import type { SiteData } from './shared' + const data: SiteData export default data } diff --git a/src/node/plugin.ts b/src/node/plugin.ts index 89188f5c0267..220012cde68b 100644 --- a/src/node/plugin.ts +++ b/src/node/plugin.ts @@ -126,7 +126,9 @@ export async function createVitePressPlugin( if (config.command === 'build') { data = { ...siteData, head: [] } } - return `export default ${JSON.stringify(JSON.stringify(data))}` + return `export default JSON.parse(${JSON.stringify( + JSON.stringify(data) + )})` } },