转载自:https://blog.csdn.net/zhangyunchou2015/article/details/147196628

1. VitePress 是什么?

VitePress 是一个基于 ViteVue 3静态站点生成器 (Static Site Generator, SSG)。它旨在提供极致的开发体验高性能的最终产出,特别适合用于构建技术文档、博客、作品集等内容驱动的网站。

核心优势

  • 极速开发启动:得益于 Vite,开发服务器启动速度极快,几乎是瞬间完成。
  • 闪电般的热更新 (HMR):修改 Markdown 或 Vue 组件时,页面更新迅速,无需等待。
  • 优化后的构建性能:基于 Vite 的 Rollup 构建,速度快,产物体积小。
  • Vue 3 驱动:利用 Vue 3 的 Composition API 和新特性,提供更灵活的定制能力。
  • Markdown 中心:专注于 Markdown 内容的编写体验,并提供强大的扩展功能。
  • 默认主题优秀:开箱即用的默认主题美观且功能完善,包含深色模式、响应式设计等。

与 VuePress 的关系

VitePress 可以看作是 VuePress 的精神继承者,但底层构建工具从 Webpack 换成了 Vite。这带来了开发体验和构建性能上的巨大提升。虽然 API 不完全兼容(尤其是 Vue 3 vs Vue 2 的差异),但核心概念(如 Markdown 驱动、配置方式)有相似之处。VitePress 更轻量、更专注于 SSG,而 VuePress 1.x 功能更全面但相对笨重。

2. 核心概念

Vite:下一代前端构建工具

Vite 利用浏览器原生的 ES 模块(ESM)支持,在开发环境下实现了按需编译,无需打包整个应用,从而大大加快了冷启动和热更新速度。

Vue 3:渐进式 JavaScript 框架

VitePress 使用 Vue 3 作为其视图层框架。这意味着你可以在 Markdown 文件中无缝使用 Vue 组件,并通过 Vue 的响应式系统和 Composition API 来构建复杂的用户界面或交互逻辑。

Markdown 驱动的内容

网站的主要内容通过 Markdown 文件编写。VitePress 使用 Markdown-it 作为 Markdown 解析器,并内置了许多实用的扩展,如表格、代码高亮、Frontmatter 等。

静态站点生成 (SSG)

VitePress 在构建时会将你的 Markdown 文件和 Vue 组件预渲染成静态 HTML 文件。这使得最终部署的网站加载速度快,SEO 友好,并且可以直接托管在任何静态文件服务器或 CDN 上。

3. 安装与基本设置

环境准备

  • 确保你的系统安装了 Node.js >= 18.0.0

初始化项目

推荐使用官方的脚手架工具来创建项目:

# 使用 npm
npm init vitepress@latest my-docs

# 使用 yarn
yarn create vitepress my-docs

# 使用 pnpm
pnpm create vitepress my-docs

根据提示进行选择(可以选择主题、添加 TypeScript 支持等)。

项目结构

一个基本的 VitePress 项目结构如下:

my-docs/
├── docs/                     # 存放 Markdown 内容文件和静态资源
│   ├── .vitepress/           # VitePress 相关配置和主题代码
│   │   ├── config.js         # 配置文件 (或 config.ts)
│   │   └── theme/            # (可选) 自定义主题目录
│   │       └── index.js      # (可选) 主题入口文件
│   ├── api-examples.md
│   ├── markdown-examples.md
│   └── index.md              # 网站首页
├── node_modules/
└── package.json
  • docs: 存放所有 Markdown 内容的地方。.vitepress 目录除外。
  • docs/.vitepress: VitePress 的“心脏”,包含配置文件、主题、自定义组件等。
  • docs/index.md: 默认的首页文件。

运行开发服务器

进入项目目录,安装依赖并启动开发服务器:

cd my-docs
npm install  # 或 yarn install / pnpm install
npm run docs:dev # 或 yarn docs:dev / pnpm docs:dev

之后,在浏览器中打开 http://localhost:5173 (端口可能变化) 即可看到你的站点。

构建站点

将你的站点构建为静态文件:

npm run docs:build # 或 yarn docs:build / pnpm docs:build

构建产物会输出到 docs/.vitepress/dist 目录。

4. 配置 VitePress (.vitepress/config.js)

这是 VitePress 的核心配置文件,你可以在这里定义站点的元数据、导航、侧边栏、主题选项等。

基础配置

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

export default defineConfig({
  lang: 'zh-CN',            // 网站语言
  title: 'My Awesome Docs', // 网站标题
  description: 'A VitePress Site', // 网站描述 (用于 SEO)
  base: '/',                // 部署站点的基础路径 (例如 /my-docs/)

  // 控制页面 <head> 标签
  head: [
    ['link', { rel: 'icon', href: '/favicon.ico' }] // 添加网站图标
  ],

  // 最后更新时间显示
  lastUpdated: true,
  lastUpdatedText: '上次更新', // 自定义文本

  // 其他配置...
  themeConfig: { /* ... */ }
})

主题配置 (themeConfig)

themeConfig 对象用于配置默认主题的各个部分。

导航栏 (nav)

定义顶部导航链接。

// .vitepress/config.js
export default defineConfig({
  // ...
  themeConfig: {
    nav: [
      { text: '指南', link: '/guide/' },
      { text: '组件', link: '/components/button' },
      {
        text: '相关链接',
        items: [
          { text: 'Vite', link: 'https://vitejs.dev/' },
          { text: 'Vue 3', link: 'https://vuejs.org/' },
          { text: 'GitHub', link: 'https://github.com/...' }
        ]
      }
    ]
  }
})
侧边栏 (sidebar)

侧边栏配置相对复杂,可以有多种形式:

  1. 多侧边栏 (基于路径):为不同路径下的页面提供不同的侧边栏。

    // .vitepress/config.js
    export default defineConfig({
      // ...
      themeConfig: {
        sidebar: {
          '/guide/': [
            {
              text: '基础',
              items: [
                { text: '简介', link: '/guide/introduction' },
                { text: '快速上手', link: '/guide/getting-started' },
              ]
            },
            {
              text: '进阶',
              items: [
                { text: '配置', link: '/guide/configuration' },
                { text: '部署', link: '/guide/deployment' },
              ]
            }
          ],
          '/components/': [
            {
              text: '通用组件',
              items: [
                { text: 'Button 按钮', link: '/components/button' },
                { text: 'Icon 图标', link: '/components/icon' },
              ]
            }
          ]
        }
      }
    })
  2. 单侧边栏 (数组形式):整个站点共享一个侧边栏结构(适用于简单站点)。

    // .vitepress/config.js
    export default defineConfig({
      // ...
      themeConfig: {
        sidebar: [
           {
              text: '基础',
              items: [ /* ... */ ]
            },
            {
              text: '组件',
              items: [ /* ... */ ]
            }
        ]
      }
    })
社交链接 (socialLinks)

在导航栏右侧显示社交媒体图标链接。

// .vitepress/config.js
export default defineConfig({
  // ...
  themeConfig: {
    socialLinks: [
      { icon: 'github', link: 'https://github.com/vuejs/vitepress' },
      { icon: 'twitter', link: '...' },
      // 可以自定义 SVG 图标
      {
        icon: {
          svg: '<svg>...</svg>'
        },
        link: '...'
      }
    ]
  }
})
其他常用配置
// .vitepress/config.js
export default defineConfig({
  // ...
  themeConfig: {
    // 编辑此页链接
    editLink: {
      pattern: 'https://github.com/your-repo/edit/main/docs/:path', // :path 会被替换为文件路径
      text: '在 GitHub 上编辑此页'
    },

    // 底部信息
    footer: {
      message: '基于 MIT 许可发布',
      copyright: `版权所有 © 2023-${new Date().getFullYear()} Your Name`
    },

    // Algolia DocSearch (需要申请)
    // algolia: {
    //   appId: '...',
    //   apiKey: '...',
    //   indexName: '...'
    // },

    // 碳广告 (Carbon Ads)
    // carbonAds: {
    //   code: 'YOUR_CARBON_CODE',
    //   placement: 'YOUR_CARBON_PLACEMENT'
    // }
  }
})

5. 内容编写 (Markdown 扩展)

VitePress 极大地增强了 Markdown 的能力。

Frontmatter

每个 Markdown 文件可以包含一个 YAML Frontmatter 块,用于定义页面特定的元数据。

---
# .vitepress/config.js 中定义的 title 的默认值
title: 页面标题 (覆盖默认)
description: 页面描述
layout: page # 使用不同的布局 (例如 'home', 'page', 'doc')
editLink: false # 禁用此页的编辑链接
lastUpdated: false # 禁用此页的最后更新时间
outline: deep # 控制右侧大纲的深度,可以是数字或 'deep'
# 自定义数据,可以在 Vue 组件中访问
myCustomData:
  foo: bar
---

# 页面内容开始...

这里是页面的主要内容。

在 Markdown 中使用 Vue

你可以直接在 Markdown 文件中嵌入 Vue 组件和表达式:

---
title: Vue in Markdown
---

# 在 Markdown 中使用 Vue

这是一个 Vue 插值表达式:{{ 1 + 1 }}

<span v-for="i in 3">循环渲染 {{ i }} </span>

<!-- 使用全局注册或导入的 Vue 组件 -->
<MyCustomComponent :prop="value" />

<script setup>
import MyCustomComponent from './MyCustomComponent.vue' // 相对路径导入
import { ref } from 'vue'

const value = ref('Hello from Script Setup!')
</script>

<style scoped>
/* 页面特定的样式 */
span {
  color: red;
}
</style>

内置组件

VitePress 提供了一些方便的内置组件:

  • <Badge />: 用于显示状态标签。

    <Badge text="测试版" type="warning" />
    <Badge text="新功能" type="tip" />
    <Badge text="已弃用" type="danger" />

代码块增强

  • 语法高亮: 默认支持多种语言。

  • 行号: 在语言标识符后添加 {line-numbers}

    ​```js{line-numbers}
    function greet(name) {
      console.log(`Hello, ${name}!`);
    }
    greet('VitePress');
    ​```
  • 行高亮: 使用 {数字}{起始行-结束行}

    ​```js{2, 4-5}
    function greet(name) { // [!code highlight]
      // 这行不会高亮
      console.log(`Hello, ${name}!`); // [!code highlight]
      return true; // [!code highlight]
    }
    greet('VitePress');
    ​```
  • 代码聚焦: 使用 // [!code focus] 或指定行号 {focus: 行号}

    ​```js{focus:2-3}
    function greet(name) {
      console.log(`Hello, ${name}!`); // [!code focus]
      return true; // [!code focus]
    }
    greet('VitePress');
    ​```
  • 代码组: 使用 ::: code-group 创建标签页切换代码块。

    ::: code-group
    ​```bash [npm]
    npm install vitepress
    ​```
    ​```bash [yarn]
    yarn add vitepress -D
    ​```
    ​```bash [pnpm]
    pnpm add vitepress -D
    ​```
    :::

自定义容器

使用特定的标记创建不同样式的提示框。

::: tip
这是一个提示信息。
:::

::: warning
这是一个警告信息。
:::

::: danger
这是一个危险/错误信息。
:::

::: details 点击展开详情
这里是隐藏的详细内容。
:::

6. 主题化与自定义

虽然默认主题很棒,但你可能需要进行定制。

使用 CSS 变量

默认主题定义了许多 CSS 变量,你可以覆盖它们来自定义颜色、字体等。在 .vitepress/theme/style.css (如果不存在则创建) 中添加:

/* .vitepress/theme/style.css */

/* 覆盖默认主题变量 */
:root {
  --vp-c-brand-1: #646cff; /* 主品牌色 */
  --vp-c-brand-2: #747bff; /* 主品牌色 hover */
  --vp-home-hero-name-color: transparent; /* 首页标题渐变效果 */
  --vp-home-hero-name-background: -webkit-linear-gradient(120deg, #bd34fe 30%, #41d1ff);

  --vp-font-family-base: 'Operator Mono', 'Source Code Pro', monospace; /* 基础字体 */
}

/* 深色模式下的变量 */
:root.dark {
  --vp-c-brand-1: #8a91ff;
  --vp-c-brand-2: #a0a7ff;
}

你需要在 .vitepress/theme/index.js 中导入这个 CSS 文件(如果 index.js 不存在,需要创建它并扩展默认主题):

// .vitepress/theme/index.js
import DefaultTheme from 'vitepress/theme'
import './style.css' // 导入自定义 CSS

export default DefaultTheme

自定义 CSS

直接在 style.css 中编写你需要的 CSS 规则,覆盖默认样式或添加新样式。

扩展默认主题

如果你需要更复杂的定制,比如注册全局组件或使用 Vue Router 的 enhanceApp 功能,可以扩展默认主题:

// .vitepress/theme/index.js
import DefaultTheme from 'vitepress/theme'
import MyGlobalComponent from './MyGlobalComponent.vue' // 你的全局组件
import './style.css'

export default {
  ...DefaultTheme, // 继承默认主题的所有配置

  // 扩展 enhanceApp,用于注册全局组件、应用插件等
  enhanceApp({ app, router, siteData }) {
    // app 是 Vue 实例
    app.component('MyGlobalComponent', MyGlobalComponent)

    // router 是 Vue Router 实例
    // siteData 是包含配置和 frontmatter 的响应式对象
  }
}

使用自定义布局

VitePress 允许你为特定页面指定不同的布局(通过 Frontmatter 的 layout 字段)。你可以在 .vitepress/theme 目录下创建 Vue 组件作为布局。默认主题提供了几个布局槽位 (Layout Slots) 让你注入内容到特定区域,而无需完全替换布局。

<!-- .vitepress/theme/MyCustomLayout.vue -->
<template>
  <div>
    <h1>我的自定义布局</h1>
    <!-- 使用 <Content /> 渲染 Markdown 内容 -->
    <Content />
  </div>
</template>
---
layout: MyCustomLayout
---

这段内容将会在 MyCustomLayout 组件的 `<Content />` 位置渲染。

或者,使用布局槽位扩展默认布局:

// .vitepress/theme/index.js
import DefaultTheme from 'vitepress/theme'
import MyCustomDocFooter from './MyCustomDocFooter.vue'
import { h } from 'vue'

export default {
  ...DefaultTheme,
  Layout() {
    return h(DefaultTheme.Layout, null, {
      // 渲染 'doc-footer-before' 插槽
      'doc-footer-before': () => h(MyCustomDocFooter)
      // 其他可用的插槽:
      // 'nav-bar-title-before', 'nav-bar-title-after', 'nav-bar-content-before', 'nav-bar-content-after',
      // 'nav-screen-content-before', 'nav-screen-content-after',
      // 'sidebar-nav-before', 'sidebar-nav-after',
      // 'aside-top', 'aside-bottom', 'aside-outline-before', 'aside-outline-after',
      // 'doc-before', 'doc-after', 'doc-footer-before',
      // 'page-top', 'page-bottom'
    })
  }
}

7. 部署

构建

运行构建命令:

npm run docs:build

静态文件将生成在 docs/.vitepress/dist 目录中。

部署平台示例

你可以将 docs/.vitepress/dist 目录的内容部署到任何静态托管平台。

GitHub Pages
  1. 配置 base: 如果你的仓库名为 my-repo,并且你想部署到 https://<username>.github.io/my-repo/,则设置 base: '/my-repo/'config.js 中。如果部署到 https://<username>.github.io,则 base: '/'

  2. 推送 dist 目录:

    • 手动: 将 dist 目录的内容推送到 gh-pages 分支。
    • 使用 GitHub Actions: 创建一个 workflow 文件 (.github/workflows/deploy.yml) 自动化构建和部署过程。
    # .github/workflows/deploy.yml
    name: Deploy VitePress site to Pages
    
    on:
      push:
        branches: [main] # 监听 main 分支的 push 事件
      workflow_dispatch: # 允许手动触发
    
    permissions:
      contents: read
      pages: write
      id-token: write
    
    concurrency:
      group: pages
      cancel-in-progress: false
    
    jobs:
      build:
        runs-on: ubuntu-latest
        steps:
          - name: Checkout
            uses: actions/checkout@v4
            with:
              fetch-depth: 0 # 如果需要 lastUpdated 功能
          - name: Setup Node
            uses: actions/setup-node@v4
            with:
              node-version: 18
              cache: npm # 或 yarn / pnpm
          - name: Install dependencies
            run: npm ci # 或 yarn install --frozen-lockfile / pnpm install --frozen-lockfile
          - name: Build with VitePress
            run: npm run docs:build # 或 yarn docs:build / pnpm docs:build
          - name: Upload artifact
            uses: actions/upload-pages-artifact@v2
            with:
              path: docs/.vitepress/dist
    
      deploy:
        needs: build
        runs-on: ubuntu-latest
        environment:
          name: github-pages
          url: ${{ steps.deployment.outputs.page_url }}
        steps:
          - name: Deploy to GitHub Pages
            id: deployment
            uses: actions/deploy-pages@v2
    • 配置 Pages 源: 在仓库的 Settings -> Pages 中,选择 “GitHub Actions” 作为 Source。
Netlify / Vercel

这些平台通常会自动检测 VitePress 项目。

  1. 连接你的 Git 仓库。
  2. 设置构建命令: npm run docs:build (或相应的 yarn/pnpm 命令)。
  3. 设置发布目录: docs/.vitepress/dist
  4. 设置 Node.js 版本 (确保 >= 18)。

平台会自动处理构建和部署。

8. 进阶策略与示例

策略一:构建文档站点

这是 VitePress 最常见的用途。

  • 清晰的侧边栏结构: 使用多侧边栏配置 (themeConfig.sidebar),按模块或功能组织文档。
  • 版本控制: 如果需要展示不同版本的文档,可以考虑为每个版本创建一个分支或子目录,并可能需要自定义导航/版本切换器组件。
  • API 文档: 结合自定义 Vue 组件,可以创建交互式的 API 参考,例如展示请求/响应示例、参数表格等。
  • 搜索集成: 对于大型文档,集成 Algolia DocSearch 至关重要。

策略二:搭建个人博客

VitePress 也可以用来搭建博客。

  • 内容结构: 在 docs 下创建一个 postsblog 目录存放 Markdown 博文。

  • 首页列表: 创建一个自定义布局或页面组件 (docs/index.mddocs/blog.md),使用 VitePress 的 createContentLoader API (在 config.js 或主题文件中) 来获取所有博文的元数据 (标题、日期、摘要等),并渲染成列表。

    // .vitepress/theme/helpers/loadPosts.js (示例)
    import { createContentLoader } from 'vitepress'
    
    export default createContentLoader('posts/**/*.md', {
      excerpt: true, // 提取摘要
      transform(rawData) {
        // 按日期排序,或处理其他 frontmatter 数据
        return rawData.sort((a, b) => {
          return +new Date(b.frontmatter.date) - +new Date(a.frontmatter.date)
        })
      }
    })
    
    // 在你的 Vue 组件中使用 (例如首页或博客列表页)
    // import { data as posts } from './helpers/loadPosts.js'
  • Frontmatter: 在博文的 Frontmatter 中添加 date, tags, author 等信息。

  • 样式: 可能需要自定义 CSS 来实现博客特有的样式。

策略三:多语言支持

VitePress 内建了对国际化 (i18n) 的支持。

  • 目录结构: 为每种语言创建一个子目录,并将对应的 config.js 放在该语言目录下。

    docs/
    ├── en/
    │   ├── .vitepress/
    │   │   └── config.js  # 英文配置
    │   ├── guide/
    │   └── index.md
    ├── fr/
    │   ├── .vitepress/
    │   │   └── config.js  # 法文配置
    │   ├── guide/
    │   └── index.md
    └── index.md         # 根目录,可能用于语言选择或重定向
  • 根配置 (可选): 可以在项目根目录的 vite.config.js 中配置多实例,或者使用一个简单的 index.md 进行语言跳转。

  • 主题配置: 在每种语言的 config.jsthemeConfig 中,配置 localeLinks 来显示语言切换下拉菜单。

    // en/.vitepress/config.js
    export default defineConfig({
      lang: 'en-US',
      title: 'English Docs',
      themeConfig: {
        localeLinks: {
          text: 'English',
          items: [
            { text: 'Français', link: '/fr/' } // 指向法文站点的根目录
          ]
        },
        nav: [ /* 英文导航 */ ],
        sidebar: { /* 英文侧边栏 */ }
      }
    })
    
    // fr/.vitepress/config.js
    export default defineConfig({
      lang: 'fr-FR',
      title: 'Documentation Française',
      themeConfig: {
        localeLinks: {
          text: 'Français',
          items: [
            { text: 'English', link: '/en/' } // 指向英文站点的根目录
          ]
        },
        nav: [ /* 法文导航 */ ],
        sidebar: { /* 法文侧边栏 */ }
      }
    })
  • 启动命令: 需要为每种语言指定根目录启动开发服务器或构建。

    npm run docs:dev -- --root en  # 启动英文开发服务器
    npm run docs:build -- --root en # 构建英文站点

策略四:集成 Algolia DocSearch

Algolia DocSearch 是一个流行的文档搜索解决方案。

  1. 申请: 前往 DocSearch 官网申请,提交你的文档站点 URL。

  2. 获取凭证: 审核通过后,你会获得 appId, apiKey, 和 indexName

  3. 配置: 在 .vitepress/config.jsthemeConfig 中添加 algolia 配置。

    // .vitepress/config.js
    export default defineConfig({
      // ...
      themeConfig: {
        algolia: {
          appId: 'YOUR_APP_ID',
          apiKey: 'YOUR_SEARCH_API_KEY',
          indexName: 'YOUR_INDEX_NAME',
          // 可选:本地化搜索框文字
          // searchParameters: {
          //   facetFilters: ['lang:zh-CN'], // 如果你的索引包含多语言
          // },
          // locales: {
          //   root: { // 可选:为根语言 (未指定语言时) 配置
          //     placeholder: '搜索文档',
          //     translations: { /* ... */ }
          //   },
          //   zh: { // 与你的 lang 配置匹配的小写语言代码
          //     placeholder: '搜索文档 (中文)',
          //     translations: {
          //       button: {
          //         buttonText: '搜索',
          //         buttonAriaLabel: '搜索'
          //       },
          //       modal: { /* ...更多翻译 */ }
          //     }
          //   }
          // }
        }
      }
    })

策略五:使用自定义组件增强内容

利用 Vue 组件的强大能力,可以在 Markdown 中创建更丰富、更具交互性的内容。

  • 图表: 使用 Chart.js, ECharts 等库封装成 Vue 组件,在 Markdown 中展示数据图表。

  • 交互式示例: 创建 CodeSandbox 或 StackBlitz 的嵌入组件,或者自己实现一个简单的代码编辑器和预览。

  • API Explorer: 如前所述,为 API 端点创建详细的交互式文档组件。

  • 流程图/思维导图: 使用 Mermaid.js 或其他库封装组件来渲染图表。

    <Mermaid chart="graph TD; A-->B; B-->C;"/>
    
    <script setup>
    // 假设你已经在主题中全局注册了 Mermaid 组件
    // 或在此处导入 import Mermaid from './components/Mermaid.vue'
    </script>

9. 总结

VitePress 凭借其闪电般的速度现代化的架构 (Vite + Vue 3)专注于 Markdown 的体验以及强大的可定制性,成为了构建技术文档、知识库、博客等静态网站的绝佳选择。它简化了开发流程,提高了开发效率,并能生成高性能、SEO 友好的最终站点。通过理解其核心概念、掌握配置方法并结合进阶策略,你可以利用 VitePress 构建出专业且用户体验良好的在线内容平台。