自动生成侧边栏

rspress.config.ts
import { join } from 'path';
import { readdirSync, statSync } from 'fs';
 
export default defineConfig({
	themeConfig: {
		sidebar: {
			'/': [
				{
					text: '首页',
					link: 'index'
				},
				...getDirStructure(join(__dirname, 'docs'), '')
			]
		}
	}
});
 
function getDirStructure(dirPath: string, relativePath: string) {
	const result: any[] = [];
	const items = readdirSync(dirPath);
 
	for (const item of items) {
		const fullPath = join(dirPath, item);
		const stat = statSync(fullPath);
 
		if (item === 'assets' || item === 'public') continue;
 
		const index = parseInt(item.split('_')[0]);
		if (stat.isDirectory()) {
			if (index) {
				result[index] = {
					text: item.split('_')[1],
					collapsed: true,
					items: getDirStructure(fullPath, join(relativePath, item))
				};
			} else {
				result.push({
					text: item,
					collapsed: true,
					items: getDirStructure(fullPath, join(relativePath, item))
				});
			}
		} else if (item.includes('.md') && item !== 'index.md') {
			const link = `${relativePath}/${item}`.replace(/\\/g, '/').replace('.md', '');
			if (index) {
				result[index] = link;
			} else {
				result.push(link);
			}
		}
	}
 
	return result.filter(item => Boolean(item));
}