vuePress2.x 多页面 多目录生成方案

前言

因为官网介绍的都只有一个‘一级标题’ 只有一个markdown文件
最终编译后也只有一个html文件,类似于spa 单页项目
如何才有多页项目呢
百度查询 网上插件库有很多,大部分不能用,
后来还是自己想出来的,很简单,办法如下

方案

新建文件 utils>gen-side.js

const fs = require('fs');

fs.readdir('./docs',(err,files)=>{
	if (err) {
		console.log(err);
	} else{
		const sidebar = files.filter(item=>item.indexOf('.md')>-1&&item!=='index.md');
		sidebar.unshift('index.md');
		sidebar.sort((a,b)=>{return a - b});
		const content = `module.exports =${JSON.stringify(sidebar)}`;
		fs.writeFile('./utils/sidebar.js', content, { encoding: 'utf8' }, err => {console.log(err);});
	}
})

或者

const fs = require('fs');

fs.readdir('./docs', (err, files) => {
	if (err) {
		console.log(err);
	} else {
		const sidebar = files.filter(item => item.indexOf('.md') > -1 && item !== 'index.md');
		sidebar.sort((a, b) => { return a - b });
		const sidebarFull = sidebar.map(item => ({
			text: item.substr(0, item.length - 3),
			link: item
		}))
		sidebarFull.unshift({
			text: '简介',
			link: 'index.md'
		});
		const content = `module.exports =${JSON.stringify(sidebarFull)}`;
		fs.writeFile('./utils/sidebar.js', content, { encoding: 'utf8' }, err => { console.log(err); });
	}
})

然后引入使用
[项目名]/docs/.vuepress/config.js

const sidebar = require('../../utils/sidebar');
const { defaultTheme } = require('@vuepress/theme-default')

module.exports = {
  lang: 'zh-CN',
  title: 'JavaScript高级程序设计(第4版)',
  description: 'JavaScript高级程序设计 红宝书',
  base: '/red-treasure-book/dist/',
  dest: './dist',
  head: [['script', { src: './js/head.js' }]],
  theme: defaultTheme({
    sidebar,
    navbar: [
      {
        text: '博客',
        link: 'https://www.cnblogs.com/dshvv',
      },
      {
        text: '语雀',
        link: 'https://www.yuque.com/dingshaohua',
      },
      {
        text: '关于我',
        link: 'https://www.baidu.com/s?wd=甲乙丙丁少',
      }
    ]
  })
}

每次新建了一个markdown文件的时候,只需要运行一下 node ./utils/gen-side.js 然后再启动项目即可npm run docs-dev

不同子路径中使用不同的侧边栏

如果你想在不同子路径中使用不同的侧边栏,你可以将该配置项设置为 侧边栏对象 :

export default {
  theme: defaultTheme({
    // 侧边栏对象
    // 不同子路径下的页面会使用不同的侧边栏
    sidebar: {
      '/guide/': [
        {
          text: 'Guide',
          children: ['/guide/README.md', '/guide/getting-started.md'],
        },
      ],
      '/reference/': [
        {
          text: 'Reference',
          children: ['/reference/cli.md', '/reference/config.md'],
        },
      ],
    },
  }),
}

用这个脚本 生成即可

import fs from 'fs';
import path from 'path';

// 此脚本用于vuepress生成菜单 支持不同路由对应不同目录(我这里只支持两层嵌套目录)
const travel = (dir) => {
  const sidebar = {};
  const handel = (dir) => {
    for (const file of fs.readdirSync(dir)) {
      if (file !== '.vuepress' && file !== 'README.md' && file !== '_category_.json' && file !== 'index.md') {
        const pathName = path.join(dir, file);
        const pathNameArr = pathName.split('\\'); // 根据这个判断当前遍历到第几次了
        if (pathNameArr.length === 2) {  // 遍历第1层的时候 将文件夹作为pathNameSpace
          sidebar[`/${file}/`] = [];
        } else if (pathNameArr.length === 3) { // 遍历第2层的时候 将文件夹作为折叠导航,文件则不导航
          if (fs.statSync(pathName).isDirectory()) {
            console.log(pathName);
            sidebar[`/${pathNameArr.at(1)}/`].push({
              text: pathNameArr.at(-1).split('_').join(' '),
              link: (pathName.replace('docs', '') + '\\index.md').split('\\').join('/'),
              collapsible: true,
              children: []
            });
          } else {
            sidebar[`/${pathNameArr.at(1)}/`].push({
              text: pathNameArr.at(-1).replace('.md', '').split('_').join(' '),
              link: pathName.replace('docs', '').split('\\').join('/')
            });
          }
        } else if (pathNameArr.length === 4) { // 遍历第3层的时候 3层的文件夹就是你的markdown,不能再有目录 我这里只支持两层嵌套目录
          const current = sidebar[`/${pathNameArr.at(1)}/`].find((item) => {
            return item.text == pathNameArr.at(2).split('_').join(' ')
          });
          current.children.push({
            text: pathNameArr.at(-1).replace('.md', '').split('_').join(' '),
            link: pathName.replace('docs', '').split('\\').join('/'),
          });
        }


        if (fs.statSync(pathName).isDirectory()) {
          handel(pathName);
        } else {

        }
      }
    }
  }
  handel(dir);
  return sidebar;
}

const sidebar = travel('docs/')
const content = `export default ${JSON.stringify(sidebar, null, 2)}`;
fs.writeFile("./utils/sidebar.ts", content, { encoding: "utf8" }, (err) => {
  console.log(err);
});

posted @ 2021-10-09 16:06  丁少华  阅读(2100)  评论(0编辑  收藏  举报