Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(seo): head content is configurable per pages #588

Closed
wants to merge 9 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 41 additions & 4 deletions docs/.vitepress/config.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
import { defineConfig } from '../../src/node'
import { defineConfig, HeadConfig, PageData } from '../../src/node'

const lang = 'en-US';
const title = 'VitePress';
const description = 'Vite & Vue powered static site generator.';

export default defineConfig({
lang: 'en-US',
title: 'VitePress',
description: 'Vite & Vue powered static site generator.',
lang,
title,
description,
lastUpdated: true,

head: getHead,

themeConfig: {
repo: 'vuejs/vitepress',
docsDir: 'docs',
Expand Down Expand Up @@ -92,3 +98,34 @@ function getConfigSidebar() {
}
]
}

function getHead(pageData: PageData): HeadConfig[] {

const site = 'https://vitepress.vuejs.org/';
const canonicalURL = `${site}${pageData.relativePath}`.replace(/.md$/, '.html');

return [
// Twitter
['meta', { name: 'twitter:card', content: 'summary_large_image' }],
['meta', { name: 'twitter:site', content: '@vuejs' }],
['meta', { name: 'twitter:title', content: pageData.title }],
['meta', { name: 'twitter:description', content: pageData.description || description }],

// Open Graph
['meta', { property: 'og:type', content: 'website' }],
['meta', { property: 'og:locale', content: lang }],
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

og:locale uses underscore instead of the BCP 47 hyphen in HTML lang to separate the subtags, so language tags like en-US should be converted to en_US.

['meta', { property: 'og:site', content: site }],
['meta', { property: 'og:site_name', content: 'VitePress' }],
['meta', { property: 'og:title', content: pageData.title }],
['meta', { property: 'og:description', content: pageData.description || description }],

// Canonical
[
'link',
{
rel: 'canonical',
href: canonicalURL,
},
]
]
}
21 changes: 2 additions & 19 deletions src/client/app/composables/head.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { watchEffect, Ref } from 'vue'
import { HeadConfig, SiteData } from '../../shared'
import { HeadConfig, processHead, SiteData } from '../../shared'
import { Route } from '../router'

export function useUpdateHead(route: Route, siteDataByRouteRef: Ref<SiteData>) {
Expand Down Expand Up @@ -58,19 +58,14 @@ export function useUpdateHead(route: Route, siteDataByRouteRef: Ref<SiteData>) {
const siteData = siteDataByRouteRef.value
const pageTitle = pageData && pageData.title
const pageDescription = pageData && pageData.description
const frontmatterHead = pageData && pageData.frontmatter.head

// update title and description
document.title = (pageTitle ? pageTitle + ` | ` : ``) + siteData.title
document
.querySelector(`meta[name=description]`)!
.setAttribute('content', pageDescription || siteData.description)

updateHeadTags([
// site head can only change during dev
...(import.meta.env.DEV ? siteData.head : []),
...(frontmatterHead ? filterOutHeadDescription(frontmatterHead) : [])
])
updateHeadTags(processHead(siteData.head, pageData));
})
}

Expand All @@ -84,15 +79,3 @@ function createHeadElement([tag, attrs, innerHTML]: HeadConfig) {
}
return el
}

function isMetaDescription(headConfig: HeadConfig) {
return (
headConfig[0] === 'meta' &&
headConfig[1] &&
headConfig[1].name === 'description'
)
}

function filterOutHeadDescription(head: HeadConfig[]) {
return head.filter((h) => !isMetaDescription(h))
}
34 changes: 2 additions & 32 deletions src/node/build/render.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import path from 'path'
import fs from 'fs-extra'
import { SiteConfig, resolveSiteDataByRoute } from '../config'
import { HeadConfig } from '../shared'
import { HeadConfig, processHead } from '../shared'
import { normalizePath, transformWithEsbuild } from 'vite'
import { RollupOutput, OutputChunk, OutputAsset } from 'rollup'
import { slash } from '../utils/slash'
Expand Down Expand Up @@ -97,11 +97,7 @@ export async function renderPage(
? `${pageData.title} | ${siteData.title}`
: siteData.title

const head = addSocialTags(
title,
...siteData.head,
...filterOutHeadDescription(pageData.frontmatter.head)
)
const head = processHead(siteData.head, pageData)

let inlinedScript = ''
if (config.mpa && result) {
Expand Down Expand Up @@ -207,29 +203,3 @@ function renderAttrs(attrs: Record<string, string>): string {
})
.join('')
}

function isMetaDescription(headConfig: HeadConfig) {
const [type, attrs] = headConfig
return type === 'meta' && attrs?.name === 'description'
}

function filterOutHeadDescription(head: HeadConfig[] | undefined) {
return head ? head.filter((h) => !isMetaDescription(h)) : []
}

function hasTag(head: HeadConfig[], tag: HeadConfig) {
const [tagType, tagAttrs] = tag
const [attr, value] = Object.entries(tagAttrs)[0] // First key
return head.some(([type, attrs]) => type === tagType && attrs[attr] === value)
}

function addSocialTags(title: string, ...head: HeadConfig[]) {
const tags: HeadConfig[] = [
['meta', { name: 'twitter:title', content: title }],
['meta', { property: 'og:title', content: title }]
]
tags.filter((tagAttrs) => {
if (!hasTag(head, tagAttrs)) head.push(tagAttrs)
})
return head
}
3 changes: 2 additions & 1 deletion src/node/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
import { Options as VuePluginOptions } from '@vitejs/plugin-vue'
import {
SiteData,
PageData,
HeadConfig,
LocaleConfig,
createLangDictionary,
Expand All @@ -33,7 +34,7 @@ export interface UserConfig<ThemeConfig = any> {
base?: string
title?: string
description?: string
head?: HeadConfig[]
head?: HeadConfig[] | ((pageData: PageData) => HeadConfig[])
themeConfig?: ThemeConfig
locales?: Record<string, LocaleConfig>
markdown?: MarkdownOptions
Expand Down
1 change: 1 addition & 0 deletions src/node/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export * from './markdown/markdown'
// shared types
export type {
SiteData,
PageData,
HeadConfig,
Header,
LocaleConfig,
Expand Down
19 changes: 18 additions & 1 deletion src/shared/shared.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { LocaleConfig, SiteData } from '../../types/shared'
import {
HeadConfig,
LocaleConfig,
SiteData,
PageData
} from '../../types/shared'

export type {
SiteData,
Expand Down Expand Up @@ -95,3 +100,15 @@ function cleanRoute(siteData: SiteData, route: string): string {

return route.slice(baseWithoutSuffix.length)
}

/**
* Process `head` configuration.
*/
export function processHead(
head: HeadConfig[] | ((pageData: PageData) => HeadConfig[]),
pageData: PageData
): HeadConfig[] {
const combineHead = !head ? [] : typeof head === 'function' ? head(pageData) : head
const frontmatterHead = pageData && pageData.frontmatter.head
return [...combineHead, ...(frontmatterHead || [])]
}
2 changes: 1 addition & 1 deletion types/shared.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export interface SiteData<ThemeConfig = any> {
lang: string
title: string
description: string
head: HeadConfig[]
head: HeadConfig[] | ((pageData: PageData) => HeadConfig[])
themeConfig: ThemeConfig
scrollOffset: number | string
locales: Record<string, LocaleConfig>
Expand Down