Skip to content

开源项目文档站

本案例展示如何使用 VitePress 为开源项目构建专业的文档站点,包括 README 集成、贡献指南、版本管理等功能。

项目概述

目标

构建一个功能完善的开源项目文档站,包含:

  • 项目介绍和快速开始
  • 完整的 API 文档
  • 贡献指南和行为准则
  • 版本历史和更新日志
  • 与 GitHub 的深度集成

目录结构

my-project/
├── docs/
│   ├── .vitepress/
│   │   ├── config.mts
│   │   └── theme/
│   │       ├── index.ts
│   │       └── custom.css
│   ├── public/
│   │   ├── images/
│   │   │   └── logo.svg
│   │   └── favicon.ico
│   ├── guide/
│   │   ├── index.md
│   │   ├── getting-started.md
│   │   ├── installation.md
│   │   └── configuration.md
│   ├── api/
│   │   ├── index.md
│   │   └── methods.md
│   ├── examples/
│   │   └── basic.md
│   ├── contribute/
│   │   ├── index.md
│   │   ├── guide.md
│   │   └── code-of-conduct.md
│   ├── changelog.md
│   ├── license.md
│   └── index.md
├── src/
│   └── ...(源代码)
├── README.md
├── LICENSE
├── CONTRIBUTING.md
├── CODE_OF_CONDUCT.md
├── CHANGELOG.md
└── package.json

配置详解

主配置文件

ts
// docs/.vitepress/config.mts
import { defineConfig } from 'vitepress'
import { version } from '../../package.json'

export default defineConfig({
  title: 'My Project',
  description: '一个优秀的开源项目',
  version,
  
  // GitHub 仓库配置
  lastUpdated: true,
  cleanUrls: true,
  
  head: [
    ['meta', { name: 'theme-color', content: '#3eaf7c' }],
    ['meta', { name: 'twitter:card', content: 'summary_large_image' }],
    ['link', { rel: 'icon', href: '/favicon.ico' }]
  ],
  
  themeConfig: {
    // Logo
    logo: '/images/logo.svg',
    siteTitle: 'My Project',
    
    // 导航栏
    nav: [
      { text: '指南', link: '/guide/' },
      { text: 'API', link: '/api/' },
      { text: '示例', link: '/examples/' },
      { text: '贡献', link: '/contribute/' },
      {
        text: `v${version}`,
        items: [
          { text: '更新日志', link: '/changelog' },
          { text: 'GitHub', link: 'https://github.com/user/my-project' }
        ]
      }
    ],
    
    // 侧边栏
    sidebar: {
      '/guide/': [
        {
          text: '开始',
          items: [
            { text: '介绍', link: '/guide/' },
            { text: '快速开始', link: '/guide/getting-started' },
            { text: '安装', link: '/guide/installation' }
          ]
        },
        {
          text: '核心概念',
          items: [
            { text: '配置', link: '/guide/configuration' },
            { text: '架构', link: '/guide/architecture' }
          ]
        }
      ],
      '/api/': [
        {
          text: 'API 参考',
          items: [
            { text: '概览', link: '/api/' },
            { text: '方法', link: '/api/methods' }
          ]
        }
      ],
      '/contribute/': [
        {
          text: '贡献指南',
          items: [
            { text: '如何贡献', link: '/contribute/' },
            { text: '开发指南', link: '/contribute/guide' },
            { text: '行为准则', link: '/contribute/code-of-conduct' }
          ]
        }
      ]
    },
    
    // 社交链接
    socialLinks: [
      { icon: 'github', link: 'https://github.com/user/my-project' },
      { icon: 'twitter', link: 'https://twitter.com/myproject' },
      { icon: 'discord', link: 'https://discord.gg/myproject' }
    ],
    
    // 页脚
    footer: {
      message: '基于 MIT 许可发布',
      copyright: `Copyright © ${new Date().getFullYear()} My Project Team`
    },
    
    // 编辑链接
    editLink: {
      pattern: 'https://github.com/user/my-project/edit/main/docs/:path',
      text: '在 GitHub 上编辑此页'
    },
    
    // GitHub 链接
    repo: 'user/my-project',
    docsDir: 'docs',
    docsBranch: 'main'
  }
})

页面内容

首页

markdown
<!-- docs/index.md -->
---
layout: home

hero:
  name: "My Project"
  text: "简洁、高效、强大"
  tagline: 一个优秀的开源项目
  image:
    src: /images/hero.png
    alt: My Project
  actions:
    - theme: brand
      text: 快速开始
      link: /guide/getting-started
    - theme: alt
      text: 在 GitHub 查看
      link: https://github.com/user/my-project

features:
  - icon: 🚀
    title: 极速性能
    details: 毫秒级响应,极致优化
  - icon: 🔧
    title: 高度可配置
    details: 灵活的配置选项满足各种需求
  - icon: 🛡️
    title: 类型安全
    details: 完整的 TypeScript 支持
  - icon: 📦
    title: 零依赖
    details: 轻量级,无第三方依赖
---

快速开始页面

markdown
<!-- docs/guide/getting-started.md -->
---
title: 快速开始
---

# 快速开始

本指南将帮助你在几分钟内开始使用 My Project。

## 环境要求

- Node.js 18.0 或更高版本
- npm、yarn 或 pnpm

## 安装

::: code-group

```bash [npm]
npm install my-project
bash
yarn add my-project
bash
pnpm add my-project

:::

基本用法

js
import { createApp } from 'my-project'

const app = createApp({
  // 配置选项
})

app.start()

下一步


### API 文档页面

```markdown
<!-- docs/api/methods.md -->
---
title: API 方法
---

# API 方法

本页面介绍 My Project 提供的所有方法。

## 核心方法

### createApp

创建应用实例。

```ts
function createApp(options: AppOptions): App

参数

参数类型必填说明
optionsAppOptions应用配置选项

返回值

返回 App 实例。

示例

ts
import { createApp } from 'my-project'

const app = createApp({
  debug: true,
  plugins: []
})

app.use

安装插件。

ts
app.use(plugin: Plugin, options?: PluginOptions): App

示例

ts
import { myPlugin } from 'my-project/plugins'

app.use(myPlugin, {
  enabled: true
})

配置选项

AppOptions

ts
interface AppOptions {
  /**
   * 是否启用调试模式
   * @default false
   */
  debug?: boolean
  
  /**
   * 插件列表
   */
  plugins?: Plugin[]
  
  /**
   * 自定义配置
   */
  config?: Record<string, any>
}

## GitHub 集成

### 自动同步 README

创建脚本同步 README 到文档:

```js
// scripts/sync-readme.js
const fs = require('fs')
const path = require('path')

// 读取 README
const readme = fs.readFileSync('README.md', 'utf-8')

// 转换为文档格式
const doc = `---
title: 项目简介
---

${readme}
  .replace(/<!--[\s\S]*?-->/g, '') // 移除注释
  .replace(/\[([^\]]+)\]\((?!https?:)([^)]+)\)/g, '[$1](/guide/$2)') // 转换相对链接
}

// 写入文档
fs.writeFileSync('docs/guide/index.md', doc)

贡献指南页面

markdown
<!-- docs/contribute/guide.md -->
---
title: 开发指南
---

# 开发指南

感谢你有兴趣为 My Project 做贡献!

## 开发环境设置

### 1. 克隆仓库

```bash
git clone https://github.com/user/my-project.git
cd my-project

2. 安装依赖

bash
npm install

3. 启动开发服务器

bash
npm run dev

4. 构建文档

bash
npm run docs:dev

项目结构

my-project/
├── src/          # 源代码
│   ├── core/     # 核心逻辑
│   └── utils/    # 工具函数
├── tests/        # 测试文件
├── docs/         # 文档
└── examples/     # 示例

提交规范

我们使用 Conventional Commits 规范:

  • feat: 新功能
  • fix: 修复 Bug
  • docs: 文档更新
  • style: 代码格式
  • refactor: 重构
  • test: 测试相关
  • chore: 构建/工具

Pull Request 流程

  1. Fork 本仓库
  2. 创建特性分支 (git checkout -b feature/amazing-feature)
  3. 提交更改 (git commit -m 'feat: add amazing feature')
  4. 推送到分支 (git push origin feature/amazing-feature)
  5. 创建 Pull Request

代码风格

我们使用 ESLint 和 Prettier:

bash
# 检查代码风格
npm run lint

# 自动修复
npm run lint:fix

### 行为准则

```markdown
<!-- docs/contribute/code-of-conduct.md -->
---
title: 行为准则
---

# 行为准则

## 我们的承诺

为了营造开放和友好的环境,我们作为贡献者和维护者承诺:无论年龄、体型、残疾、种族、性别认同和表达、经验水平、教育程度、社会经济地位、国籍、外貌、种族、宗教或性取向如何,参与我们的项目和社区都将为每个人提供无骚扰的体验。

## 我们的标准

积极行为示例:

- 使用友好和包容的语言
- 尊重不同的观点和经验
- 优雅地接受建设性批评
- 关注对社区最有利的事情
- 对其他社区成员表示同理心

不可接受的行为示例:

- 使用性化的语言或图像
- 挑衅、侮辱/贬损评论以及人身或政治攻击
- 公开或私下的骚扰
- 未经明确许可,发布他人的私人信息
- 其他在专业环境中可能被合理认为不适当的行为

## 责任

项目维护者负责阐明可接受行为的标准,并期望对任何不可接受行为采取适当和公平的纠正措施。

## 范围

本行为准则适用于项目空间和公共空间。

## 执行

可以通过 [email@example.com](mailto:email@example.com) 联系项目团队来报告辱骂、骚扰或其他不可接受的行为。

## 归属

本行为准则改编自 [Contributor Covenant](https://www.contributor-covenant.org/),版本 2.0。

版本管理

多版本文档

ts
// docs/.vitepress/config.mts
import { defineConfig } from 'vitepress'

export default defineConfig({
  // 版本化重写
  rewrites: {
    'v1/:path': 'v1/:path',
    'v2/:path': 'v2/:path'
  },
  
  themeConfig: {
    nav: [
      {
        text: '版本',
        items: [
          { text: 'v2 (当前)', link: '/' },
          { text: 'v1 (维护)', link: '/v1/' },
          { text: 'v0 (已弃用)', link: '/v0/', badge: { text: '弃用', type: 'danger' } }
        ]
      }
    ]
  }
})

版本选择器组件

vue
<!-- docs/.vitepress/components/VersionSelector.vue -->
<template>
  <div class="version-selector">
    <select v-model="selectedVersion" @change="navigate">
      <option value="/">v{{ currentVersion }} (当前)</option>
      <option value="/v1/">v1.x (LTS)</option>
      <option value="/v0/">v0.x (已弃用)</option>
    </select>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vitepress'

const router = useRouter()
const currentVersion = '2.0'
const selectedVersion = ref('/')

function navigate() {
  router.go(selectedVersion.value)
}
</script>

更新日志

markdown
<!-- docs/changelog.md -->
---
title: 更新日志
---

# 更新日志

本项目的所有重要更改都将记录在此文件中。

格式基于 [Keep a Changelog](https://keepachangelog.com/),
版本遵循 [语义化版本](https://semver.org/)。

## [2.0.0] - 2026-04-01

### 新增

- 全新的 API 设计
- TypeScript 支持
- 插件系统

### 变更

- 重构核心模块
- 更新依赖版本

### 修复

- 修复内存泄漏问题
- 修复边界情况处理

### 移除

- 移除废弃的 API

## [1.5.0] - 2025-12-01

### 新增

- 新增 `createApp` 方法
- 支持自定义配置

### 修复

- 修复类型定义

## [1.0.0] - 2025-06-01

首次正式发布!

自动化部署

GitHub Actions

yaml
# .github/workflows/docs.yml
name: Deploy Docs

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

jobs:
  build-and-deploy:
    runs-on: ubuntu-latest
    
    steps:
      - uses: actions/checkout@v4
      
      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'npm'
      
      - name: Install dependencies
        run: npm ci
      
      - name: Build docs
        run: npm run docs:build
      
      - name: Deploy to GitHub Pages
        if: github.event_name == 'push'
        uses: peaceiris/actions-gh-pages@v3
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          publish_dir: docs/.vitepress/dist

发布流程

json
// package.json
{
  "scripts": {
    "docs:dev": "vitepress dev docs",
    "docs:build": "vitepress build docs",
    "docs:preview": "vitepress preview docs",
    "release": "standard-version",
    "release:minor": "standard-version --release-as minor",
    "release:major": "standard-version --release-as major"
  }
}

最佳实践总结

实践说明
版本化文档维护多个版本的文档
自动同步同步 README 和贡献指南
GitHub 集成利用 GitHub 功能增强协作
CI/CD 自动化自动构建和部署
清晰的导航让用户快速找到所需信息
完整的 API 文档提供详细的 API 参考

相关资源

贡献者

加载中...

想要成为贡献者?

在 CNB 上参与贡献