auto-routes.ts 6.1 KB
import type { Plugin } from "vite";

import type { RouteGeneratorOptions } from "../utils/route-generator";

import { existsSync, writeFileSync } from "node:fs";
import { dirname, resolve } from "node:path";
import process from "node:process";
import { fileURLToPath, pathToFileURL } from "node:url";

export interface AutoRoutesOptions {
	// 自定义路由生成规则
	customRules?: RouteGeneratorOptions["customRules"];
	// 排除的文件或目录
	exclude?: (RegExp | string)[];
	// 生成的路由文件路径
	outputFile?: string;
	// 路由前缀
	routePrefix?: string;
	// views 目录路径(相对于项目根目录)
	viewsDir?: string;
	// 是否在开发模式下监听文件变化
	watch?: boolean;
}

/**
 * Vite 插件:自动生成路由
 */
export function autoRoutes(options: AutoRoutesOptions = {}): Plugin {
	const {
		viewsDir = "src/views",
		outputFile = "src/router/auto-routes.ts",
		routePrefix = "",
		exclude = [ "components", "components/", "NotFound.vue" ],
		watch = true,
		customRules,
	} = options;

	 
	const projectRoot = process.cwd();
	const viewsPath = resolve(projectRoot, viewsDir);
	const outputPath = resolve(projectRoot, outputFile);

	// 确保输出目录存在
	const outputDir = resolve(outputPath, "..");
	if (!existsSync(outputDir)) {
		throw new Error(`Output directory does not exist: ${outputDir}`);
	}

	/**
	 * 生成路由文件
	 */
	async function generateRouteFile() {
		try {
			// 使用 import.meta.url 构建绝对路径,避免相对路径解析问题
			const currentFileUrl = import.meta.url;
			const currentFilePath = fileURLToPath(currentFileUrl);
			const currentDir = dirname(currentFilePath);
			const routeGeneratorPath = resolve(currentDir, "../utils/route-generator.ts");
			
			// 在 Windows 上,动态导入需要使用 file:// URL 格式
			const routeGeneratorUrl = pathToFileURL(routeGeneratorPath).href;
			
			// 使用 file:// URL 进行动态导入
			const { generateRoutes } = await import(routeGeneratorUrl);
			
			const routes = generateRoutes({
				viewsDir: viewsPath,
				routePrefix,
				exclude,
				customRules,
			});

			// 将路由转换为代码字符串
			 
			function routeToCode(route: any, indent: number = 0): string {
				const indentStr = "  ".repeat(indent);
				const parts: string[] = [];
				parts.push(`${indentStr}{`);

				// path
				if (route.path) {
					parts.push(`${indentStr}  path: ${JSON.stringify(route.path)},`);
				}

				// component - 需要特殊处理
				if (route.component) {
					// 从 component 函数中提取路径
					const componentStr = route.component.toString();
					const importMatch = componentStr.match(/import\(['"]([^'"]+)['"]\)/);
					if (importMatch) {
						const importPath = importMatch[1];
						parts.push(`${indentStr}  component: () => import(${JSON.stringify(importPath)}),`);
					}
				}

				// id, title, icon, level, hidden - 顶层字段
				if (route.id !== undefined) {
					parts.push(`${indentStr}  id: ${JSON.stringify(route.id)},`);
				}
				if (route.title !== undefined) {
					parts.push(`${indentStr}  title: ${JSON.stringify(route.title)},`);
				}
				if (route.icon !== undefined) {
					parts.push(`${indentStr}  icon: ${JSON.stringify(route.icon)},`);
				}
				if (route.level !== undefined) {
					parts.push(`${indentStr}  level: ${route.level},`);
				}
				if (route.hidden !== undefined) {
					parts.push(`${indentStr}  hidden: ${route.hidden},`);
				}

				// meta
				if (route.meta && Object.keys(route.meta).length > 0) {
					const metaStr = JSON.stringify(route.meta, null, 2)
						.split("\n")
						.map((line, i) => i === 0 ? line : `${indentStr}  ${line}`)
						.join("\n");
					parts.push(`${indentStr}  meta: ${metaStr},`);
				}

				// children
				if (route.children && route.children.length > 0) {
					parts.push(`${indentStr}  children: [`);
					 
					route.children.forEach((child: any, index: number) => {
						parts.push(routeToCode(child, indent + 2));
						if (index < route.children.length - 1) {
							parts[parts.length - 1] += ",";
						}
					});
					parts.push(`${indentStr}  ],`);
				}

				parts.push(`${indentStr}}`);
				return parts.join("\n");
			}

			 
			const routesCode = routes.map((route: any) => routeToCode(route, 0)).join(",\n");

			// 生成文件内容
			const content = `// 此文件由 auto-routes 插件自动生成,请勿手动编辑
// 如需自定义路由,请在 vite.config.ts 中配置 customRules
// 生成时间: ${new Date().toLocaleString("zh-CN")}

import type { RouteRecordRaw } from 'vue-router';

export const autoRoutes: RouteRecordRaw[] = [
${routesCode}
];
`;

			writeFileSync(outputPath, content, "utf8");
			console.log(`[auto-routes] ✓ 路由文件已生成: ${outputPath} (${routes.length} 个路由)`);
		} catch (error) {
			console.error("[auto-routes] ✗ 生成路由文件失败:", error);
		}
	}

	return {
		name: "auto-routes",
		enforce: "pre",

		// 构建开始时生成路由
		async buildStart() {
			await generateRouteFile();
		},

		// 开发服务器启动时生成路由
		configureServer(server) {
			if (watch) {
				// 监听 views 目录变化
				server.watcher.add(viewsPath);
				server.watcher.on("change", async (file) => {
					if (file.includes(viewsPath)) {
						console.log(`[auto-routes] 检测到文件变化: ${file}`);
						await generateRouteFile();
					}
				});
				server.watcher.on("add", async (file) => {
					if (file.includes(viewsPath)) {
						console.log(`[auto-routes] 检测到新文件: ${file}`);
						await generateRouteFile();
					}
				});
				server.watcher.on("unlink", async (file) => {
					if (file.includes(viewsPath)) {
						console.log(`[auto-routes] 检测到文件删除: ${file}`);
						await generateRouteFile();
					}
				});
			}
		},

		// 开发模式下,每次请求时检查是否需要重新生成
		async handleHotUpdate({ file, server }) {
			// eslint-disable-next-line regexp/no-unused-capturing-group
			if (file.includes(viewsPath) && /\.(vue|tsx|jsx)$/u.test(file)) {
				console.log(`[auto-routes] 热更新: ${file}`);
				await generateRouteFile();
				// 触发客户端重新加载路由
				server.ws.send({
					type: "full-reload",
				});
			}
		},
	};
}