VuePress实现自动获取文章侧边栏目录功能

请添加图片描述

‍ 热爱摄影的程序员
‍ 喜欢编码的设计师
擅长设计的剪辑师
‍ 一位高冷无情的编码爱好者
大家好,我是 DevOps 工程师
欢迎分享 / 收藏 / 赞 / 在看!

【需求】

通常情况下,在使用 VuePress 时需要指定 sidebar 的内容,但是如果我们的文章很多,每次都需要手动指定,这样就很麻烦,所以我们可以通过自动获取文章侧边栏目录的方式来解决这个问题。

VuePress实现自动获取文章侧边栏目录功能_第1张图片

【解决】

docs/.vuepress/utils 新建如下代码,读取指定目录下的所有.md文件,并按照文件名从大到小排列,返回文件名数组:

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

/**
 * 读取指定目录下的所有.md文件,按照文件名从大到小排列
 * @param relativePath 相对路径
 * @returns {string[]|*[]} 文件名数组
 */
function findMdFiles(relativePath) {
    const directoryPath = path.join(process.cwd() + '/docs/', relativePath); // 使用process.cwd()来获取当前工作目录并构建目录路径

    try {
        const files = fs.readdirSync(directoryPath);

        // 筛选出以.md为后缀的文件名并排除README.md
        const mdFiles = files
            .filter((file) => file.endsWith('.md') && file !== 'README.md')
            .map((file) => path.parse(file).name);

        // 按照从大到小排序
        mdFiles.sort((a, b) => {
            const aNum = parseInt(a.slice(1));
            const bNum = parseInt(b.slice(1));
            return bNum - aNum;
        });
        console.log(mdFiles);

        return mdFiles;
    } catch (error) {
        console.error(`Error reading directory ${directoryPath}: ${error}`);
        return [];
    }
}

module.exports = {
    findMdFiles
};

这样,我们就可以在 docs/.vuepress/config.js 中使用了:

const path = require('./utils/path.js');

// 其他代码

'/aaa/': [
    {
        title: '编程干货',
        collapsable: true,
        children: path.findMdFiles('/aaa/')
    }
]

代码将获取 docs/aaa 目录下的所有 .md 文件,并按照文件名从大到小排列,然后将其作为侧边栏的目录。

你可能感兴趣的:(编程干货,javascript,前端,开发语言,vue)