# A3. VuePress动态生成目录
为了根据文件夹结构动态生成目录,而不是手动指定每个文件,我们可以使用 Node.js 脚本等工具来动态生成目录配置,然后在配置文件中引入。
# 1. 创建一个脚本 generateSidebar.js
const fs = require('fs');
const path = require('path');
const generateSidebar = (folderPath) => {
const files = fs.readdirSync(folderPath);
return files.map(file => `/${folderPath}/${file}`);
};
const sidebarConfig = {
'/section1/': generateSidebar('section1'),
'/section2/': generateSidebar('section2')
};
fs.writeFileSync(path.resolve(__dirname, '.vuepress/sidebarConfig.js'), `module.exports = ${JSON.stringify(sidebarConfig, null, 2)}`);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
运行上述脚本文件后,将获得配置信息文件sidebarConfig.js。
# 2. 在配置文件中引入生成的配置信息
const sidebarConfig = require('./.vuepress/sidebarConfig.js');
module.exports = {
themeConfig: {
sidebar: sidebarConfig
}
};
1
2
3
4
5
6
7
2
3
4
5
6
7