使用VitePress搭建组件库文档
安装
首先在根目录下新建 docs 文件夹,并执行pnpm init,然后安装vitepress
pnpm init
pnpm install vitepress -D -w
在docs 目录下运行
npx vitepress init
Where should VitePress initialize the config? // 在哪初始化项目的配置目录?
Site title: //网站标题:
Site description: //网站描述:
Theme: //主题:
Use TypeScript for config and theme files? //使用TypeScript?
Add VitePress npm scripts to package.json? // 是否将VitePress npm脚本添加到package.json?
下面是我的选项 ./就在此目录创建项目,网站标题和网站描述可以后期修改,使用的默认样式,不实用ts 不添加npm
修改package.json文件 内容为:
{
"name": "site_docs",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "vitepress dev",
"build": "vitepress build",
"preview": "vitepress preview"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@story/components": "workspace:^"
},
"devDependencies": {
"postcss": "^8.4.33"
}
}
安装 postcss 防止vitePress 的样式上污染组件的样式
pnpm add postcss -D
在docs 目录下新建 postcss.config.mjs文件, 内容为
import { postcssIsolateStyles } from 'vitepress'
export default {
plugins: [
postcssIsolateStyles({
includeFiles: [/vp-doc\.css/] // defaults to /base\.css/
})
]
}
在根目录的pnpm-workspace-yaml 文件内添加docs工作区
packages:
- packages/*
- example
- docs
在docs目录下安装我们的插件
pnpm add @story/components -D
全局挂载组件
在.vitepress目录下新建theme/index.js 文件 内容为
// https://vitepress.dev/guide/custom-theme
import { h } from 'vue'
import DefaultTheme from 'vitepress/theme'
import story from '@story/components'
/** @type {import('vitepress').Theme} */
export default {
extends: DefaultTheme,
Layout: () => {
return h(DefaultTheme.Layout, null, {
// https://vitepress.dev/guide/extending-default-theme#layout-slots
})
},
enhanceApp({ app, router, siteData }) {
// ...
app.use(story)
}
}
修改.vitepress/config.mjs 添加我们的文档链接 vitepress 配置请参考官网 https://vitepress.dev/zh/
import { defineConfig } from 'vitepress'
// https://vitepress.dev/reference/site-config
export default defineConfig({
title: "My Awesome Project",
description: "A VitePress Site",
themeConfig: {
// https://vitepress.dev/reference/default-theme-config
nav: [
{ text: '组件', link: '/views/card.md' },
],
socialLinks: [
{ icon: 'github', link: 'https://github.com/vuejs/vitepress' }
]
}
})
组件文档编写
在docs目录下新建views/card.md 内容为
# Card 卡片
## 默认卡片样式
<s-card class="vp-raw" title="xxxx">
<div>the custom card</div>
<div>the custom card</div>
<div>the custom card</div>
</s-card>
:::details 展开代码
:::code-group
```html
<s-card title="这是标题">
<div>the custom card</div>
<div>the custom card</div>
<div>the custom card</div>
</s-card>
``
运行 pnpm run dev
在页面中点击组件就可以看到我们刚刚写的组件文档了
vitepress 具体配置详情请参考官方文档或者网上教程 https://vitepress.dev/zh/
这是我配置的