Skip to content

Sitemap 生成

VitePress 提供开箱即用的 sitemap.xml 生成支持。要启用它,请将以下内容添加到你的 .vitepress/config.js

js
// .vitepress/config.js
export default {
  sitemap: {
    hostname: 'https://example.com'
  }
}

要在 sitemap.xml 中包含 <lastmod> 标签,你可以启用 lastUpdated 选项:

js
// .vitepress/config.js
export default {
  lastUpdated: true,
  sitemap: {
    hostname: 'https://example.com'
  }
}

选项

Sitemap 支持以下选项:

ts
export interface SitemapConfig {
  /**
   * 网站的主机名(必需)
   * @example 'https://example.com'
   */
  hostname: string
  /**
   * 要从 sitemap 中排除的路径
   * 支持字符串和正则表达式模式
   * @example ['/secret', /private/]
   */
  exclude?: (string | RegExp)[]
  /**
   * 包含在 sitemap 中的额外 URL
   * @example ['https://example.com/extra-page']
   */
  include?: string[]
  /**
   * 转换 URL 的函数
   * @param url - 要转换的 URL
   * @param base - 站点的基础路径
   * @returns 转换后的 URL
   */
  transformItems?: (items: SitemapItem[]) => SitemapItem[] | Promise<SitemapItem[]>
}

export interface SitemapItem {
  url: string
  changefreq?: 'always' | 'hourly' | 'daily' | 'weekly' | 'monthly' | 'yearly' | 'never'
  lastmod?: string
  priority?: number
}

示例配置

排除页面

js
// .vitepress/config.js
export default {
  sitemap: {
    hostname: 'https://example.com',
    exclude: ['/secret', '/admin/**', /private/]
  }
}

包含额外页面

js
// .vitepress/config.js
export default {
  sitemap: {
    hostname: 'https://example.com',
    include: [
      'https://example.com/extra-page',
      'https://example.com/another-page'
    ]
  }
}

转换 sitemap 项目

js
// .vitepress/config.js
export default {
  sitemap: {
    hostname: 'https://example.com',
    transformItems: (items) => {
      // 为所有页面添加自定义属性
      return items.map((item) => ({
        ...item,
        changefreq: 'weekly',
        priority: item.url === '/' ? 1.0 : 0.8
      }))
    }
  }
}

动态 sitemap 生成

你也可以使用数据加载器动态生成 sitemap:

js
// .vitepress/config.js
import { loadData } from 'vitepress'

const posts = loadData('posts.data.js')

export default {
  sitemap: {
    hostname: 'https://example.com',
    transformItems: (items) => {
      // 添加博客文章到 sitemap
      const blogItems = posts.map((post) => ({
        url: post.url,
        lastmod: post.date,
        changefreq: 'monthly',
        priority: 0.7
      }))
      
      return [...items, ...blogItems]
    }
  }
}

输出

启用 sitemap 生成后,VitePress 将在构建时在输出目录的根目录中生成 sitemap.xml 文件。

生成的 sitemap 将包含:

  • 所有页面的 URL
  • 最后修改日期(如果启用了 lastUpdated
  • 变更频率和优先级(如果在 transformItems 中指定)

提交到搜索引擎

生成 sitemap 后,你应该将其提交给搜索引擎以改善你的网站的 SEO:

你也可以在你的 robots.txt 文件中引用 sitemap:

# public/robots.txt
User-agent: *
Allow: /

Sitemap: https://example.com/sitemap.xml

vitepress开发指南