【vuepress】自动生成侧边栏

前言

VuePress是尤雨溪尤大为了支持 Vue 及其子项目的文档需求而写的一个项目,VuePress界面十分简洁,并且非常容易上手,花少量时间就可以将项目架构搭好

问题

由于官网文档里面写的都是怎么生成侧边栏,必须将每个文档的路由进行配置,没有写怎么自动生成侧边栏,这样一来文档一多的话就很麻烦了,所以查阅了网上很多资料,写了个遍历方法,自动生成侧边栏

源码

//侧边栏
// const autosidebar = require('vuepress-auto-sidebar-doumjun')
const fs = require('fs')
const path = require('path')
function getChildren(path,sort=true) {
let root = []
readDirSync(path,root)
root=root.map(item=>{
    if(item.split('/')[4]){
        return item.split('/')[3]+'/'+item.split('/')[4]
    }else{
        return item.split('/')[3]
    }
    
})
//排序
if(sort){
let sortList=[]
let nosortList=[]
root.forEach(item=>{
	if(Number(item.replace(".md","").match(/[^-]*$/))){
    	sortList.push(item)
    }else{
    	nosortList.push(item)
    }
})
    root=sortList.sort(function(a,b){
        return a.replace(".md","").match(/[^-]*$/)-b.replace(".md","").match(/[^-]*$/)
    }).concat(nosortList)
}

    return root
}
function readDirSync(path,root){
var pa = fs.readdirSync(path);
pa.forEach(function(ele,index){
var info = fs.statSync(path+"/"+ele)
if(info.isDirectory()) {
readDirSync(path+ele,root)
} else {
if (checkFileType(ele)) {
root.push(prefixPath(path,ele))
}
}
})
}
function checkFileType(path) {
return path.includes(".md")
}
function prefixPath(basePath,dirPath) {
let index = basePath.indexOf("/")
// 去除一级目录地址
basePath = basePath.slice(index,path.length)
// replace用于处理windows电脑的路径用\表示的问题
return path.join(basePath,dirPath).replace(/\\/g,"/")
}
module.exports = {getChildren:getChildren}

插件vuepress-sidebar-atuo

为了方便大家使用,不用劳心劳力的去引用,所以我根据以上方法封装了一个插件

使用方法

下载

npm i vuepress-sidebar-atuo

引入

侧边栏配置文件内引入
const {getChildren} = require(“vuepress-sidebar-atuo”)

使用

module.exports = {
‘/views/’: [
{
title: ‘基础知识’,
collapsable: true,
children: getChildren(‘./docs/views/basis/’)
},
{
title: ‘高级进阶’,
collapsable: true,
children: getChildren(‘./docs/views/advanced/’)
},
‘/jottings/’:[
{
title: ‘随笔’,
collapsable: true,
children: getChildren(‘./docs/jottings/’)
},
],
//…
这样就配置完成了
排序
-文件名格式 不设置则排最后 数值越小,越靠前

xxxxx-01, xxxxx-02, xxxxx-03 …

查看效果—>

插件源码 github

博客效果 malunan的blog

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值