should update head in production as well

pull/1/head
Evan You 4 years ago
parent f3d1a98f95
commit 04fe864ad8

@ -1,5 +1,4 @@
#!/usr/bin/env node #!/usr/bin/env node
const path = require('path')
const chalk = require('chalk') const chalk = require('chalk')
const argv = require('minimist')(process.argv.slice(2)) const argv = require('minimist')(process.argv.slice(2))
@ -18,11 +17,11 @@ if (!command || command === 'dev') {
console.log(`listening at http://localhost:${port}`) console.log(`listening at http://localhost:${port}`)
}) })
}).catch(err => { }).catch(err => {
console.error(`failed to start server. error: `, err) console.error(chalk.red(`failed to start server. error:\n`), err)
}) })
} else if (command === 'build') { } else if (command === 'build') {
require('../dist').build(argv).catch(err => { require('../dist').build(argv).catch(err => {
console.error(`build error: `, err) console.error(chalk.red(`build error:\n`), err)
}) })
} else { } else {
console.log(chalk.red(`unknown command "${command}".`)) console.log(chalk.red(`unknown command "${command}".`))

@ -5,33 +5,29 @@ import { siteDataRef } from './siteData'
* @param {import('./pageData').PageDataRef} pageDataRef * @param {import('./pageData').PageDataRef} pageDataRef
*/ */
export function useUpdateHead(pageDataRef) { export function useUpdateHead(pageDataRef) {
const descriptionTag = createHeadElement(['meta', {
name: 'description',
content: siteDataRef.value.description
}])
document.head.appendChild(descriptionTag)
/** /**
* @type {HTMLElement[]} * @type {HTMLElement[]}
*/ */
const siteHeadTags = [] const metaTags = Array.from(document.querySelectorAll('meta'))
/**
* @type {HTMLElement[]}
*/
const pageHeadTags = []
let isFirstUpdate = true
/** /**
* @param {HTMLElement[]} tags
* @param {import('src').HeadConfig[]} newTags * @param {import('src').HeadConfig[]} newTags
*/ */
const updateHeadTags = (tags, newTags) => { const updateHeadTags = (newTags) => {
tags.forEach((el) => document.head.removeChild(el)) if (!__DEV__ && isFirstUpdate) {
tags.length = 0 // in production, the initial meta tags are already pre-rendered so we
// skip the first update.
isFirstUpdate = false
return
}
metaTags.forEach((el) => document.head.removeChild(el))
metaTags.length = 0
if (newTags && newTags.length) { if (newTags && newTags.length) {
newTags.forEach((headConfig) => { newTags.forEach((headConfig) => {
const el = createHeadElement(headConfig) const el = createHeadElement(headConfig)
document.head.appendChild(el) document.head.appendChild(el)
tags.push(el) metaTags.push(el)
}) })
} }
} }
@ -41,12 +37,14 @@ export function useUpdateHead(pageDataRef) {
const siteData = siteDataRef.value const siteData = siteDataRef.value
const pageTitle = pageData && pageData.title const pageTitle = pageData && pageData.title
document.title = (pageTitle ? pageTitle + ` | ` : ``) + siteData.title document.title = (pageTitle ? pageTitle + ` | ` : ``) + siteData.title
descriptionTag.setAttribute('content', siteData.description) updateHeadTags([
updateHeadTags(siteHeadTags, siteData.head) ['meta', {
updateHeadTags( name: 'description',
pageHeadTags, content: siteData.description
pageData && pageData.frontmatter.head }],
) ...siteData.head,
...(pageData && pageData.frontmatter.head || [])
])
}) })
} }

@ -16,11 +16,12 @@ export function createApp() {
// distinct per-request. // distinct per-request.
const pageDataRef = ref() const pageDataRef = ref()
if (__DEV__ && inBrowser) { if (inBrowser) {
// dynamically update head tags during dev since it's an SPA // dynamically update head tags
// this is not needed in production.
useUpdateHead(pageDataRef) useUpdateHead(pageDataRef)
}
if (__DEV__ && inBrowser) {
// hot reload pageData // hot reload pageData
hot.on('vitepress:pageData', (data) => { hot.on('vitepress:pageData', (data) => {
if ( if (

@ -20,6 +20,6 @@ export async function build(buildOptions: BuildOptions = {}) {
} }
} finally { } finally {
await fs.rmdir(siteConfig.tempDir, { recursive: true }) await fs.rmdir(siteConfig.tempDir, { recursive: true })
console.log('done.')
} }
console.log('done.')
} }

@ -24,17 +24,18 @@ export async function renderPage(
'_assets', '_assets',
pageJsPath pageJsPath
)) ))
const pageData = JSON.parse(__pageData)
const html = ` const html = `
<html lang="en-US"> <html lang="en-US">
<head> <head>
<title>${__pageData.title ? __pageData.title + ` | ` : ``}${ <title>${pageData.title ? pageData.title + ` | ` : ``}${
config.site.title config.site.title
}</title> }</title>
<meta name="description" content="${config.site.description}"> <meta name="description" content="${config.site.description}">
<link rel="stylesheet" href="${assetPath}/style.css">${renderHead( <link rel="stylesheet" href="${assetPath}/style.css">${renderHead(
config.site.head config.site.head
)}${renderHead(__pageData.frontmatter.head)} )}${renderHead(pageData.frontmatter.head)}
</head> </head>
<body> <body>
<div id="app">${content}</div> <div id="app">${content}</div>

Loading…
Cancel
Save