为什么要自动生产侧边栏
各个组件库中会有多个组件,多个说明文档。我们需要在config.js中对侧边栏进行配置,每个组件库都需要对应的配置且每个组件库的配置也会有所不同,新增一个组件文档就需要改一下配置,维护麻烦。可不可以自动生成侧边栏?
实现思路
利用node的fs递归去获取文档的目录结构,根据获取到的目录结构生成对应的侧边栏结构(去除掉不该生成目录的文件或文件夹),则新增一个组件文档则会自动在侧边栏生成对应项。
具体代码
const shelljs = require('shelljs');
const fs = require('fs');
const path = require('path');
//忽略的文件夹
const IGNORE_DIR = ["image",'img',"images","imgs","assets",".vuepress"]
//遍历文件夹
function readDirToObjTreeTool(){
let foldPath = shelljs.pwd().stdout // 当前目录的绝对路径
let objTree = []
function recursion(foldPath, data) {
let files = fs.readdirSync(foldPath)
// 1.目录循环
files.forEach(item => {
//是否是目录
let isDir = fs.statSync(`${foldPath}/${item}`).isDirectory()
// 判断逻辑:是文件,并且不是以 .开头的隐藏文件,并且不是 node_modules && build
if (isDir && IGNORE_DIR.indexOf(item)===-1) {
data.push({
name: item,
children: [],
path: `${foldPath}/${item}`,
isDir
})
} else if (!isDir && item !== '.DS_Store') {
data.push({
name: item,
isDir
});
}
})
data.forEach(item => {
if (item.isDir) {
recursion(item.path, item.children)
}
})
}
recursion(path.join(foldPath,'docs'), objTree)
return objTree
}
//创建侧边导航栏
function createSideBar(){
const dirData = readDirToObjTreeTool();
const sidebar = {};
const recursion = (path, _dirData) => {
const _data = [];
_dirData.forEach(data => {
const _path = `${path}/${data.name}`;
if (data.isDir) {
_data.push({
title: data.name,
collapsable: true,
children: recursion(_path, data.children)
})
return;
}
const names = data.name.split(".");
//不是MD文件不生成对应侧边栏
if(names[names.length-1].toUpperCase() !== "MD"){
return;
}
//README.MD文件侧边栏名称为【快速开始】
if(data.name.toUpperCase() === "README.MD"){
_data.unshift(["","快速开始"]);
return;
}
_data.push([_path,data.name.slice(0, data.name.lastIndexOf("."))]);
})
return _data;
}
dirData.forEach(_dir => {
const path = `/${_dir.name}`;
if (_dir.isDir) {
sidebar[`${path}/`] = [{
title: _dir.name,
collapsable: false,
children:recursion(path, _dir.children)
}]
} else {
sidebar[path.slice(0, path.lastIndexOf("."))] = [path]
}
});
return sidebar;
}