启动

1
npm run docs:dev

自动设置侧边栏

默认侧边栏全部手敲,文件一多就很麻烦,自动设置侧边栏原理讲解

  1. 项目根目录新建文件utils/auto_set_sidebar.mjs

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    import path from "node:path";
    import fs from "node:fs";

    // 文件根目录
    const DIR_PATH = path.resolve();
    // 白名单,过滤不是文章的文件和文件夹
    const WHITE_LIST = [
    "index.md",
    ".vitepress",
    "node_modules",
    ".idea",
    "assets",
    ];

    // 判断是否是文件夹
    const isDirectory = (path) => fs.lstatSync(path).isDirectory();

    // 取差值
    const intersections = (arr1, arr2) =>
    Array.from(new Set(arr1.filter((item) => !new Set(arr2).has(item))));

    // 把方法导出直接使用
    function getList(params, path1, pathname) {
    // 存放结果
    const res = [];
    // 开始遍历params
    for (let file in params) {
    // 拼接目录
    const dir = path.join(path1, params[file]);
    // 判断是否是文件夹
    const isDir = isDirectory(dir);
    if (isDir) {
    // 如果是文件夹,读取之后作为下一次递归参数
    const files = fs.readdirSync(dir);
    res.push({
    text: params[file],
    collapsible: true,
    items: getList(files, dir, `${pathname}/${params[file]}`),
    });
    } else {
    // 获取名字
    const name = path.basename(params[file]);
    // 排除非 md 文件
    const suffix = path.extname(params[file]);
    if (suffix !== ".md") {
    continue;
    }
    res.push({
    text: name,
    link: `${pathname}/${name}`,
    });
    }
    }
    // 对name做一下处理,把后缀删除
    res.map((item) => {
    item.text = item.text.replace(/\.md$/, "");
    });
    return res;
    }

    export const set_sidebar = (pathname) => {
    // 获取pathname的路径
    const dirPath = path.join(DIR_PATH, pathname);
    // 读取pathname下的所有文件或者文件夹
    const files = fs.readdirSync(dirPath);
    // 过滤掉
    const items = intersections(files, WHITE_LIST);
    // getList 函数后面会讲到
    return getList(items, dirPath, pathname);
    };
  2. 导入配置文件``.vitepress\config.mts`

    1
    import {auto_set_sidebar} from '../utils/auto_set_sidebar.mjs'
  3. 若想让目录blog下的文档自动生成侧边栏,首先目录下要有首页index.md,否则404,然后修改主题配置的的 sidebar 配置项

    1
    sidebar: {'/blog': auto_set_sidebar('blog')}, 

    这个auto_set_sidebar传递的参数是相对于根路径的文件夹路径,返回的是每个文件夹中文件的名称和链接