自动生成vitepress侧边栏
第一步
代码如下:utils.js
js
// 要先安装 path fs 插件
import * as path from 'path';
import * as fs from 'fs'
// 动态生成侧边栏函数
export const walk = function (dir, subDir = '') {
const url = path.join(__dirname, dir)
let childList = [];
const list = fs.readdirSync(url);
list.forEach((file) => {
if (path.extname(file) === '.md') {
// 类型为文件此操作
const { name = '' } = path.parse(file)
const cDir = dir.split('').filter(item => item !== '.').join('')
const link = `${cDir}/${name}`
childList.push({
text: name,
link
})
}
})
const results = [
{
text: subDir,
collapsed: false,
items: childList
}
]
return results
};
第二步
代码如下:clientSidbar.js
js
import {walk} from "./utils";
// javascript模块
const jsDir = '../client/js';
export const jsSidebar = walk(jsDir,'JavaScript');
第三步
代码如下:config.mts
ts
import { jsSidebar } from '../script/clientSidebar'
export default defineConfig({
sidebar: {
'/client/js': jsSidebar,
}
})
文件目录
plaintext
U+251C
docs
├── .vitepress
│ ├── config.mts
│ └── theme
│ │ ├── index.js
│ │ └── custom.scss
├── home
│ ├── 零零碎碎
│ │ └── 1.vitepress自动生成侧边栏.md
├── client
│ ├── js
│ │ └── 1.vitepress自动生成侧边栏.md
├── script
│ ├── clientSidebar.js
│ └── utils.js
└── index.md