[vitepress 学习] 搭建一个文档

3,059 阅读2分钟

什么是 VitePress?

VuePress 是一个基于 vue 的文档工具

VitePress is VuePress' little brother, built on top of Vite.

VitePress 是它小弟弟,基于 vite

动机

VuePress 是基于 webpack, 而 VitePress 基于 vite 更精简,长篇大论略...

实现

初始化

  1. 构建一个文件夹,如果是已有项目直接跳到 3
mkdir vitepress-starter && cd vitepress-starter
  1. 初始化项目
yarn init
  1. 添加 vitepress 依赖
yarn add --dev vitepress
  1. 项目下创建一个 docs 文件夹用于放文档,并创建 index.md

  2. package.json 里添加相关 script

{
  "scripts": {
    "docs:dev": "vitepress dev docs",
    "docs:build": "vitepress build docs",
    "docs:serve": "vitepress serve docs"
  }
}

以上内容来自 官方文档

首页及相关说明

index.md 文档首页一般布局如图所示

img

vitepress 文档里有个 Frontmatter 可定义文档中相关部分内容,使用 yaml 格式

index.md 的文件内容

home: true # 作为首页

actionText: 指南 # 主链接
actionLink: /guide/ # 主链接地址

altActionText: 快速上手 # 副链接
altActionLink: /guide/getting-started # 副地址

features: # 相关特性
  - title: feature1
    details: feature1 description
  - title: feature2
    details: feature2 description
  - title: feature3
    details: feature3 description

这里链接定义方式和 vuepress 有区别,vuepress 是通过定义 actions 来实现的

标题、导航和菜单可在 config.js 里定义

配置及相关说明

一般文档的目录结构如下

.
├─ docs
│  ├─ .vitepress
│  │  └─ config.js
│  └─ index.md
└─ package.json

其中的配置 config.js 放在 .vitepress 目录下,目前版本只支持 js

基本配置如下

module.exports = {
  title: 'Hello VitePress', // 标题
  description: 'Just playing around.', // 副标题
};

接下来加入其他页面和导航目录

.
├─ docs
│  ├─ .vitepress
│  │  └─ config.js
│  ├─ guide
│  │  ├─ getting-started.md
│  │  └─ index.md
│  └─ index.md
└─ package.json
module.exports = {
  title: 'Hello VitePress', // 标题
  description: 'Just playing around.', // 副标题
  themeConfig: {
    // 顶部导航栏内容
    nav: [{ text: '指南', link: '/guide/' }],
    // 侧边栏导航内容
    sidebar: {
      '/guide/': [
        {
          text: '指南',
          children: [
            { text: '介绍', link: '/guide/' },
            { text: '快速上手', link: '/guide/getting-started' },
          ],
        },
      ],
    },
  },
};

关于页面路径和导航这里列几个常用规则

  1. 目录下 .md 文件生成后对应 .html 文件
  2. 在访问目录路径时自动跳转到 index.md 对应的 html 页,例如 /guide/ 则跳到 /guide/index.html
  3. 当前浏览器路径匹配到 sidebar 定义的 key 前缀时侧边栏会显示对应 key 的菜单
  4. nav 顶部导航弹出的下级菜单用 items 表示
  5. 如果 sidebar 某一项值是 auto,则会根据目录结构自动生成侧边栏

开发调试

根据 scripts 中的定义

yarn run docs:dev # 开发调试
yarn run docs:build # 构建
yarn run docs:serve # 作为服务运行