auto-routes.ts
6.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
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",
});
}
},
};
}