VitePress
生成站点地图
安装依赖
环境和依赖版本
node
18.xpnpm
7.xvitepress
1.0.0-alpha.51sitemap
7.1.1
sh
pnpm add -D sitemap
修改配置文件
docs/.vitepress/config.ts
ts
import { createWriteStream } from 'node:fs'
import { resolve } from 'node:path'
import { SitemapStream } from 'sitemap'
import { defineConfig, PageData } from 'vitepress'
const links: { url: string; lastmod: PageData['lastUpdated'] }[] = []
export default defineConfig({
// 其他配置项...
/* 站点地图 */
transformHtml: (_, id, { pageData }) => {
if (!/[\\/]404\.html$/.test(id))
links.push({
url: pageData.relativePath.replace(/((^|\/)index)?\.md$/, '$2'),
lastmod: pageData.lastUpdated
})
},
buildEnd: async ({ outDir }) => {
// hostname 为线上域名
const sitemap = new SitemapStream({ hostname: 'https://notes.fe-mm.com/' })
const writeStream = createWriteStream(resolve(outDir, 'sitemap.xml'))
sitemap.pipe(writeStream)
links.forEach((link) => sitemap.write(link))
sitemap.end()
await new Promise((r) => writeStream.on('finish', r))
}
})