vuepress自动生成侧边栏分组小函数

vuepress的自带路由是不好用的,当你使用自动生成时,就不能生成一级分类,只能根据文章标题建立二级标题,那么如果你想要生成一个带有一级分类的子文章,那么你需要手动配置这样的配置

{
    title: "xxx",
    collapsable: false,
    children: [
      'code-style/code',
      'code-style/browser-fix',
      'code-style/js-code'
    ]
  }

每次更新时,还需要手动向列表添加children,这是非常麻烦的,所以下面笔者提供了一个函数来处理这样的问题

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

function getChildren(path) {
  const root = []
  readDirSync(path,root)
  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
}

通过调用getChildren(basePath)方法就可以获得对应basePath目录下的所有博客,即使是子目录,函数也会帮你正确的返回!但是为了保证函数处理过程的正确性,你传的目录格式必须符合docs/xxx/xxx/,否则函数和webpack都不能正确的帮你生成数据。

为了保证你的目录是符合要求的,你可以使用仿制以下帮助函数来生成basePath

/**
 * @return {string}
 */
// xxx就是你的博客文件所在的一级目录,dirPath为二级目录
function createFilePath(dirPath) {
  return `docs/xxx/${dirPath}/`
// `docs/study/${dirPath}/`
}

你可能感兴趣的:(vuepress)