Skip to content
On this page

自动生成vitepress侧边栏脚本

编写初衷

为了方便快捷的生成侧边导航栏,不用一个一个自己手写,写了一个脚本,使用很简单

脚本如下:

js
const path = require('path');
const fs = require('fs');

// 动态生成侧边栏函数
export const walk = function (dir, subDir = '') {
	let results = [];
	const list = fs.readdirSync(dir + subDir);
	list.forEach((file) => {
		file = dir + subDir+ '/' + file;
		if (path.extname(file) === '.md') {
			results.push(file);
		}
	})
	const items = results.map((item) => {
		return {
			text: path.basename(item, '.md'),
			link: item.slice(6, -3)
		}
	}).sort((a, b) => {
		const index1 = Number(a.text.split('.')[0])
		const index2 = Number(b.text.split('.')[0])
		return index1 - index2
	})
	return {
		text: subDir,
		collapsible: true,
		collapsed: false,
		items: items
	}
};

walk函数接收两个参数, 第一个参数dir对应的是我们顶部导航栏下的一个子项,即我们的一个专题(侧面导航栏就是专门针对这个专题来生成的),第二个参数subdir对应的是专题下的多个不同部分,看下面的图会一目了然: 1670994684085.png 在给markdown起名字的时候,为了能够按照我们想要的顺序来,我给每篇文章都加上了序号,用来排序,walk函数中的sort方法就是这个作用,可以看一下我的目录结构:

bash
docs
├── backend
│   ├── nestjs
│   │   ├── NestJS基础
│   │   │   ├── 1.九大核心概念.md
│   │   │   ├── 2.核心概念小结.md
│   │   │   └── 3.ExecutionContext.md
│   │   ├── NestJS进阶
│   │   │   ├── 1.依赖注入.md
│   │   │   ├── 2.生命周期.md
│   │   │   ├── 3.打包部署(\23221).md
│   │   │   ├── 4.整合prisma(todo).md
│   │   │   ├── 5.高级配置(todo).md
│   │   │   └── 6.缓存(todo).md
│   │   ├── index.md
│   │   └── 安全认证
│   │       └── 1.登录认证(JWT).md
│   └── nginx
│       ├── index.md
│       ├── 其它
│       │   ├── 1.日志.md
│       │   ├── 2.文件关联程序.md
│       │   └── 3.HTTP状态码.md
│       ├── 基础知识
│       │   ├── 1.连接状态模块.md
│       │   ├── 2.随机主页模块.md
│       │   ├── 3.替换模块.md
│       │   ├── 4.文件读取模块.md
│       │   ├── 5.文件压缩模块.md
│       │   └── 6.页面缓存模块.md
│       └── 配置相关
│           ├── 1.默认配置.md
│           ├── 2.主配置文件.md
│           ├── 3.子配置目录.md
│           ├── 4.location.md
│           ├── 5.代理.md
│           └── 6.proxy代理.md
├── colorfulLife
│   ├── index.md
│   ├── 个人总结
│   │   └── 2022年终.md
│   └── 杂七杂八
│       └── 1.vitepress侧边栏生成脚本.md
├── frontend
├── index.md
└── public
    └── img
        └── logo.png

使用

使用时,我会把每一个专题的Sidebar配置单独抽离出来进行配置,例如下面是NestJS专题的Sidebar

js
import {walk} from "../scripts/utils";

const baseDir = './docs/backend/nestjs/'
export const nestjsSidebar = [
	walk(baseDir,'NestJS基础'),
	walk(baseDir,'NestJS进阶'),
	walk(baseDir,'安全认证'),
]

vitepress的config.js文件下配置sidebar时只需要引入这个配置就行

js
export default{
	themeConfig:{
        sidebar: {
            '/backend/nestjs/': nestjsSidebar,
        },
    }
}

这样一来,只要这个结构弄好之后,我们只需要在对应的文件夹下直接写我们的文章就行了,侧边栏目录结构会自动生成, 希望对大家有所帮助。