Commit 4947e631 by Lin

feat: 自动生成路由配置数据

1 parent 6dd252f3
{ {
"name": "@venus/venus-agentic-assisant", "name": "@venus/venus-agentic-assisant",
"version": "1.0.0", "version": "1.0.0",
"description": "Vue3 微前端子应用模板,用于与 qiankun 基座集成", "description": "汽车智能体-智能助理",
"private": true, "private": true,
"type": "module", "type": "module",
"scripts": { "scripts": {
...@@ -12,25 +12,26 @@ ...@@ -12,25 +12,26 @@
"type-check": "vue-tsc --noEmit" "type-check": "vue-tsc --noEmit"
}, },
"dependencies": { "dependencies": {
"@vue-office/docx": "catalog:", "@element-plus/icons-vue": "catalog:",
"@vue-office/pdf": "catalog:", "@js-preview/docx": "catalog:",
"@vue-office/excel": "catalog:",
"@js-preview/excel": "catalog:", "@js-preview/excel": "catalog:",
"@vue-office/pptx": "catalog:",
"@js-preview/pdf": "catalog:", "@js-preview/pdf": "catalog:",
"@js-preview/docx": "catalog:",
"@element-plus/icons-vue": "catalog:",
"@venus/tailwind-config": "workspace:*",
"@venus/common-ui-vue": "workspace:*", "@venus/common-ui-vue": "workspace:*",
"@venus/tailwind-config": "workspace:*",
"@venus/tools": "workspace:*",
"@vue-office/docx": "catalog:",
"@vue-office/excel": "catalog:",
"@vue-office/pdf": "catalog:",
"@vue-office/pptx": "catalog:",
"@vueuse/core": "catalog:", "@vueuse/core": "catalog:",
"axios": "catalog:", "axios": "catalog:",
"element-plus": "catalog:", "element-plus": "catalog:",
"glsk-oss-jssdk": "catalog:",
"pinia": "catalog:", "pinia": "catalog:",
"sass": "catalog:",
"tailwindcss": "catalog:", "tailwindcss": "catalog:",
"vue": "catalog:", "vue": "catalog:",
"vue-router": "catalog:", "vue-router": "catalog:"
"glsk-oss-jssdk": "catalog:",
"sass": "catalog:"
}, },
"devDependencies": { "devDependencies": {
......
<script setup lang="ts"> <script setup lang="ts">
import { onMounted } from 'vue'; import { onMounted } from "vue";
onMounted(() => { onMounted(() => {
// console.log('Vue3 微应用已挂载'); // console.log('Vue3 微应用已挂载');
}); });
...@@ -8,7 +9,7 @@ onMounted(() => { ...@@ -8,7 +9,7 @@ onMounted(() => {
<template> <template>
<main class="app-main"> <main class="app-main">
<router-view v-slot="{ Component }"> <router-view v-slot="{ Component }">
<transition name="fade" mode="out-in"> <transition mode="out-in" name="fade">
<component :is="Component" /> <component :is="Component" />
</transition> </transition>
</router-view> </router-view>
......
// 此文件由 auto-routes 插件自动生成,请勿手动编辑
// 如需自定义路由,请在 vite.config.ts 中配置 customRules
// 生成时间: 2026/1/22 14:01:32
import type { RouteRecordRaw } from 'vue-router';
export const autoRoutes: RouteRecordRaw[] = [
{
path: "/assistant/index",
id: "assistant",
title: "Assistant",
icon: "",
level: 0,
hidden: false,
meta: {
"authority": "assistant",
"keepAlive": false,
"requiresAuth": false,
"title": "Assistant"
},
children: [
{
path: "add-update",
id: "assistant-add-update",
title: "AddUpdate",
icon: "",
level: 2,
hidden: false,
meta: {
"authority": "assistant:add-update",
"keepAlive": false,
"order": 1,
"requiresAuth": false,
"title": "AddUpdate"
},
}
],
},
{
path: "/manage-agentic/index",
id: "manage-agentic",
title: "ManageAgentic",
icon: "",
level: 0,
hidden: false,
meta: {
"authority": "manage-agentic",
"keepAlive": false,
"requiresAuth": false,
"title": "ManageAgentic"
},
},
{
path: "/manage-konw/index",
id: "manage-konw",
title: "ManageKonw",
icon: "",
level: 0,
hidden: false,
meta: {
"authority": "manage-konw",
"keepAlive": false,
"requiresAuth": false,
"title": "ManageKonw"
},
children: [
{
path: "add-update",
id: "manage-konw-add-update",
title: "AddUpdate",
icon: "",
level: 2,
hidden: false,
meta: {
"authority": "manage-konw:add-update",
"keepAlive": false,
"order": 1,
"requiresAuth": false,
"title": "AddUpdate"
},
}
],
},
{
path: "/test/index",
id: "test",
title: "Test",
icon: "",
level: 0,
hidden: false,
meta: {
"authority": "test",
"keepAlive": false,
"requiresAuth": false,
"title": "Test"
},
},
{
path: "/communication",
id: ".-communication",
title: "Communication",
icon: "",
level: 2,
hidden: false,
meta: {
"authority": "communication",
"keepAlive": false,
"order": 1,
"requiresAuth": false,
"title": "Communication"
},
},
{
path: "/home",
id: ".-home",
title: "Home",
icon: "",
level: 2,
hidden: false,
meta: {
"authority": "home",
"keepAlive": false,
"order": 1,
"requiresAuth": false,
"title": "Home"
},
},
{
path: "/settings",
id: ".-settings",
title: "Settings",
icon: "",
level: 2,
hidden: false,
meta: {
"authority": "settings",
"keepAlive": false,
"order": 1,
"requiresAuth": false,
"title": "Settings"
},
},
{
path: "/user",
id: ".-user",
title: "User",
icon: "",
level: 2,
hidden: false,
meta: {
"authority": "user",
"keepAlive": false,
"order": 1,
"requiresAuth": false,
"title": "User"
},
},
{
path: "/:pathMatch(.*)*",
component: () => import("@/views/NotFound.vue"),
meta: {
"title": "404",
"hidden": true
},
}
];
...@@ -2,7 +2,23 @@ import type { Router, RouteRecordRaw } from 'vue-router'; ...@@ -2,7 +2,23 @@ import type { Router, RouteRecordRaw } from 'vue-router';
import { createRouter as _createRouter, createWebHistory } from 'vue-router'; import { createRouter as _createRouter, createWebHistory } from 'vue-router';
const routes: RouteRecordRaw[] = [ // 导入自动生成的路由
// 注意:使用动态导入以避免构建时错误
let autoRoutes: RouteRecordRaw[] = [];
// 使用同步方式导入(在构建时生成的文件)
// 由于项目使用 ES 模块,这里使用条件导入
try {
// @ts-ignore - 动态导入可能不存在,使用同步导入
// eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires
const autoRoutesModule = require('./auto-routes');
autoRoutes = autoRoutesModule.autoRoutes || [];
} catch (error) {
// 如果自动生成的路由文件不存在,使用手动配置的路由
console.warn('[router] 自动路由文件不存在,使用手动配置的路由');
// 手动配置的路由(作为后备方案)
autoRoutes = [
{ {
path: '/', path: '/',
name: 'Home', name: 'Home',
...@@ -80,6 +96,30 @@ const routes: RouteRecordRaw[] = [ ...@@ -80,6 +96,30 @@ const routes: RouteRecordRaw[] = [
name: 'NotFound', name: 'NotFound',
component: () => import('@/views/NotFound.vue'), component: () => import('@/views/NotFound.vue'),
}, },
];
}
// 手动配置的路由(用于覆盖或补充自动生成的路由)
// 手动配置的路由优先级更高,会覆盖自动生成的路由
const manualRoutes: RouteRecordRaw[] = [
// 可以在这里添加需要手动配置的特殊路由
// 例如:需要特殊权限、动态参数等的路由
// {
// path: '/custom',
// name: 'Custom',
// component: () => import('@/views/Custom.vue'),
// meta: {
// title: '自定义路由',
// },
// },
];
// 合并路由:手动配置的路由优先
const routes: RouteRecordRaw[] = [
...manualRoutes,
...autoRoutes.filter(
(autoRoute) => !manualRoutes.some((manualRoute) => manualRoute.path === autoRoute.path)
),
]; ];
/** /**
......
...@@ -3,8 +3,11 @@ ...@@ -3,8 +3,11 @@
"composite": true, "composite": true,
"module": "ESNext", "module": "ESNext",
"moduleResolution": "bundler", "moduleResolution": "bundler",
"paths": {
"@venus/tools/*": ["../../../../packages/tools/src/*"]
},
"allowSyntheticDefaultImports": true, "allowSyntheticDefaultImports": true,
"skipLibCheck": true "skipLibCheck": true
}, },
"include": ["vite.config.ts"] "include": ["vite.config.ts", "vite-plugins/**/*.ts"]
} }
import type { Plugin } from 'vite'; import type { Plugin } from "vite";
import { existsSync } from 'node:fs'; import { existsSync } from "node:fs";
import { resolve } from 'node:path'; import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import vue from '@vitejs/plugin-vue'; // @ts-ignore - workspace package, resolved by resolveWorkspacePackage plugin
import vueJsx from '@vitejs/plugin-vue-jsx'; import { autoRoutes } from "@venus/tools/src/vite-plugins/auto-routes";
import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite'; import vue from "@vitejs/plugin-vue";
import { defineConfig } from 'vite'; import vueJsx from "@vitejs/plugin-vue-jsx";
import qiankun from 'vite-plugin-qiankun'; import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { defineConfig } from "vite";
import qiankun from "vite-plugin-qiankun";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const PORT = 8081; const PORT = 8081;
const APP_NAME = 'assisant'; // 与基座配置的 name 一致 const APP_NAME = "assisant"; // 与基座配置的 name 一致
// 获取源码路径 // 获取源码路径
const commonUiSourcePath = resolve( const commonUiSourcePath = resolve(
__dirname, __dirname,
'../../../../packages/common-ui/vue-ui/src/index.ts', "../../../../packages/common-ui/vue-ui/src/index.ts",
);
const toolsSourcePath = resolve(
__dirname,
"../../../../packages/tools/src",
); );
// 自定义插件:强制解析 @venus/common-ui-vue // 自定义插件:强制解析 workspace 包
function resolveWorkspacePackage(): Plugin { function resolveWorkspacePackage(): Plugin {
return { return {
name: 'resolve-workspace-package', name: "resolve-workspace-package",
enforce: 'pre', // 在其他插件之前执行 enforce: "pre", // 在其他插件之前执行
resolveId(id, importer) { resolveId(id, importer) {
// 精确匹配包名 // 解析 @venus/common-ui-vue
if ( if (
id === '@venus/common-ui-vue' || id === "@venus/common-ui-vue" ||
id.startsWith('@venus/common-ui-vue/') id.startsWith("@venus/common-ui-vue/")
) { ) {
// 验证文件是否存在 // 验证文件是否存在
if (existsSync(commonUiSourcePath)) { if (existsSync(commonUiSourcePath)) {
...@@ -40,13 +51,93 @@ function resolveWorkspacePackage(): Plugin { ...@@ -40,13 +51,93 @@ function resolveWorkspacePackage(): Plugin {
`[resolve-workspace-package] 文件不存在: ${commonUiSourcePath}`, `[resolve-workspace-package] 文件不存在: ${commonUiSourcePath}`,
); );
} }
// 解析 @venus/tools
if (id.startsWith("@venus/tools/")) {
const subPath = id.replace("@venus/tools/", "");
// 处理相对路径导入(如 ../utils/route-generator)
let resolvedPath = resolve(toolsSourcePath, subPath);
// 如果是目录,尝试查找 index 文件
if (!resolvedPath.endsWith(".ts") && !resolvedPath.endsWith(".js")) {
// 尝试添加 .ts 扩展名
const resolvedPathWithExt = `${resolvedPath}.ts`;
if (existsSync(resolvedPathWithExt)) {
resolvedPath = resolvedPathWithExt;
} else {
// 尝试作为目录查找 index.ts
const indexPath = resolve(resolvedPath, "index.ts");
if (existsSync(indexPath)) {
resolvedPath = indexPath;
}
}
}
if (existsSync(resolvedPath)) {
return {
id: resolvedPath,
external: false,
};
}
}
// 处理包内部的相对路径导入(如 ../utils/route-generator.js)
// TypeScript 中使用 .js 扩展名导入 .ts 文件是标准做法
if (importer && importer.includes("packages/tools/src") && (id.startsWith("../") || id.startsWith("./"))) {
const importerDir = dirname(importer);
const resolvedPath = resolve(importerDir, id);
// 如果已经有扩展名
if (resolvedPath.endsWith(".js")) {
// TypeScript 使用 .js 扩展名导入 .ts 文件,需要替换为 .ts
const tsPath = resolvedPath.replace(/\.js$/, ".ts");
if (existsSync(tsPath)) {
return {
id: tsPath,
external: false,
};
}
// 如果 .ts 不存在,尝试使用 .js
if (existsSync(resolvedPath)) {
return {
id: resolvedPath,
external: false,
};
}
} else if (resolvedPath.endsWith(".ts")) {
// 直接使用 .ts 扩展名
if (existsSync(resolvedPath)) {
return {
id: resolvedPath,
external: false,
};
}
} else {
// 没有扩展名,尝试添加 .ts(优先)或 .js
const resolvedPathWithTs = `${resolvedPath}.ts`;
if (existsSync(resolvedPathWithTs)) {
return {
id: resolvedPathWithTs,
external: false,
};
}
const resolvedPathWithJs = `${resolvedPath}.js`;
if (existsSync(resolvedPathWithJs)) {
return {
id: resolvedPathWithJs,
external: false,
};
}
}
}
return null; return null;
}, },
}; };
} }
export default defineConfig(({ mode, command }) => { export default defineConfig(({ mode, command }) => {
const isDev = mode === 'development'; const isDev = mode === "development";
const isServe = command === 'serve'; const isServe = command === "serve";
// 生产环境使用 /child/ 前缀,确保所有资源路径都带上该前缀 // 生产环境使用 /child/ 前缀,确保所有资源路径都带上该前缀
const basePath = isDev && isServe ? `http://localhost:${PORT}/` : `/child/${APP_NAME}/`; const basePath = isDev && isServe ? `http://localhost:${PORT}/` : `/child/${APP_NAME}/`;
...@@ -54,19 +145,31 @@ export default defineConfig(({ mode, command }) => { ...@@ -54,19 +145,31 @@ export default defineConfig(({ mode, command }) => {
base: basePath, // 生产环境使用 /child/ 前缀作为基础路径,Vite 会自动应用到所有资源路径 base: basePath, // 生产环境使用 /child/ 前缀作为基础路径,Vite 会自动应用到所有资源路径
plugins: [ plugins: [
resolveWorkspacePackage(), resolveWorkspacePackage(),
// 自动路由生成插件(需要在其他插件之前执行)
autoRoutes({
viewsDir: "src/views",
outputFile: "src/router/auto-routes.ts",
routePrefix: "",
exclude: [ "components", "components/", "NotFound.vue" ],
watch: isDev, // 开发模式下监听文件变化
// 自定义路由规则示例
customRules: (filePath, routeConfig) => {
return routeConfig;
},
}),
vue(), vue(),
vueJsx(), vueJsx(),
// 自动导入 Vue 相关函数 // 自动导入 Vue 相关函数
AutoImport({ AutoImport({
imports: ['vue', 'vue-router', 'pinia'], imports: [ "vue", "vue-router", "pinia" ],
dts: 'src/auto-imports.d.ts', dts: "src/auto-imports.d.ts",
eslintrc: { eslintrc: {
enabled: false, enabled: false,
}, },
}), }),
// 自动导入组件 // 自动导入组件
Components({ Components({
dts: 'src/components.d.ts', dts: "src/components.d.ts",
}), }),
// qiankun 插件配置 // qiankun 插件配置
qiankun(APP_NAME, { qiankun(APP_NAME, {
...@@ -76,27 +179,27 @@ export default defineConfig(({ mode, command }) => { ...@@ -76,27 +179,27 @@ export default defineConfig(({ mode, command }) => {
resolve: { resolve: {
alias: [ alias: [
{ {
find: '@', find: "@",
replacement: resolve(__dirname, 'src'), replacement: resolve(__dirname, "src"),
}, },
{ {
find: '@public', find: "@public",
replacement: resolve(__dirname, 'public'), replacement: resolve(__dirname, "public"),
}, },
{ {
find: '@venus/common-ui-vue', find: "@venus/common-ui-vue",
replacement: resolve( replacement: resolve(
__dirname, __dirname,
'../../../../packages/common-ui/vue-ui/src/index.ts', "../../../../packages/common-ui/vue-ui/src/index.ts",
), ),
}, },
], ],
// 设置条件导出优先使用 development // 设置条件导出优先使用 development
conditions: ['development', 'module', 'import', 'default'], conditions: [ "development", "module", "import", "default" ],
}, },
// 优化依赖预构建,排除 workspace 包 // 优化依赖预构建,排除 workspace 包
optimizeDeps: { optimizeDeps: {
exclude: ['@venus/common-ui-vue', 'jiti'], exclude: [ "@venus/common-ui-vue", "jiti" ],
include: [], include: [],
}, },
server: { server: {
...@@ -105,24 +208,25 @@ export default defineConfig(({ mode, command }) => { ...@@ -105,24 +208,25 @@ export default defineConfig(({ mode, command }) => {
host: true, host: true,
origin: `http://localhost:${PORT}`, // 设置资源加载的 origin origin: `http://localhost:${PORT}`, // 设置资源加载的 origin
headers: { headers: {
'Access-Control-Allow-Origin': '*', // 允许所有来源 "Access-Control-Allow-Origin": "*", // 允许所有来源
}, },
}, },
build: { build: {
target: 'esnext', target: "esnext",
minify: false, // 开发环境不压缩,便于调试 minify: false, // 开发环境不压缩,便于调试
cssCodeSplit: false, // css 不拆分 cssCodeSplit: false, // css 不拆分
assetsDir: 'assets', // 资源文件目录 assetsDir: "assets", // 资源文件目录
rollupOptions: { rollupOptions: {
output: { output: {
// qiankun 需要的输出格式 // qiankun 需要的输出格式
format: 'umd', format: "umd",
// UMD 库名称,必须与应用名称一致 // UMD 库名称,必须与应用名称一致
name: `qiankunApp_${APP_NAME.replace(/-/g, '_')}`, // eslint-disable-next-line unicorn/prefer-string-replace-all
name: `qiankunApp_${APP_NAME.replace(/-/g, "_")}`,
// 资源文件路径配置,Vite 会自动将 base 路径(/child/${APP_NAME}/)应用到这些路径 // 资源文件路径配置,Vite 会自动将 base 路径(/child/${APP_NAME}/)应用到这些路径
entryFileNames: 'assets/[name].js', entryFileNames: "assets/[name].js",
chunkFileNames: 'assets/[name].[hash].js', chunkFileNames: "assets/[name].[hash].js",
assetFileNames: 'assets/[name].[hash].[ext]', assetFileNames: "assets/[name].[hash].[ext]",
// 内联所有动态导入,解决顶层 await 问题 // 内联所有动态导入,解决顶层 await 问题
inlineDynamicImports: true, inlineDynamicImports: true,
}, },
......
# @venus/tools
Venus 项目工具包,提供通用的工具函数和 Vite 插件。
## 安装
```bash
pnpm add @venus/tools
```
## 功能
### 自动路由生成插件
自动根据 `views` 目录中的文件结构生成 Vue Router 路由配置。
#### 使用方法
在 `vite.config.ts` 中配置:
```typescript
import { defineConfig } from 'vite';
import { autoRoutes } from '@venus/tools/src/vite-plugins/auto-routes';
export default defineConfig({
plugins: [
autoRoutes({
viewsDir: 'src/views', // views 目录
outputFile: 'src/router/auto-routes.ts', // 输出文件
routePrefix: '', // 路由前缀
exclude: ['components', 'NotFound.vue'], // 排除文件
watch: true, // 开发模式监听
customRules: (filePath, routeConfig) => {
// 自定义路由规则
return routeConfig;
},
}),
],
});
```
#### 配置选项
- `viewsDir`: views 目录路径(默认: `'src/views'`)
- `outputFile`: 生成的路由文件路径(默认: `'src/router/auto-routes.ts'`)
- `routePrefix`: 路由前缀(默认: `''`)
- `exclude`: 排除的文件或目录(默认: `['components', 'components/', 'NotFound.vue']`)
- `watch`: 是否在开发模式下监听文件变化(默认: `true`)
- `customRules`: 自定义路由生成规则函数
#### 路由生成规则
- **一级目录(index 文件)**:作为父路由,`level: 0`,`id` 为文件夹名小写
- **子菜单(非 index 文件)**:作为父路由的 `children`,`level: 2`,`id` 为 `文件夹名-文件名`
- **默认属性**:
- `icon`: 空字符串
- `hidden`: false
- `meta.authority`: 根据路由路径自动生成
- `meta.keepAlive`: false
- `meta.order`: 非 index 文件默认为 1
- `meta.requiresAuth`: false
## 导出
```typescript
// Vite 插件
import { autoRoutes } from '@venus/tools/src/vite-plugins/auto-routes';
import type { AutoRoutesOptions } from '@venus/tools/src/vite-plugins/auto-routes';
// 路由生成工具
import { generateRoutes, loadRouteConfig } from '@venus/tools/src/utils/route-generator';
import type { RouteConfig, RouteGeneratorOptions } from '@venus/tools/src/utils/route-generator';
```
## 开发
```bash
# 构建
pnpm build
# 类型检查
pnpm type-check
```
# 自动路由插件迁移说明
## 变更内容
自动路由生成插件已从项目本地迁移到 `@venus/tools` 包中,以便统一管理和维护。
## 迁移步骤
### 1. 安装依赖
确保 `package.json` 中包含 `@venus/tools` 依赖:
```json
{
"dependencies": {
"@venus/tools": "workspace:*"
}
}
```
### 2. 更新导入路径
**之前:**
```typescript
import { autoRoutes } from './vite-plugins/auto-routes';
```
**现在:**
```typescript
import { autoRoutes } from '@venus/tools/src/vite-plugins/auto-routes';
```
### 3. 更新类型导入(如需要)
**之前:**
```typescript
import type { RouteConfig } from '@/utils/route-generator';
```
**现在:**
```typescript
import type { RouteConfig } from '@venus/tools/src/utils/route-generator';
```
## 文件变更
### 已删除的文件
- `vite-plugins/auto-routes.ts` → 已迁移到 `packages/tools/src/vite-plugins/auto-routes.ts`
- `src/utils/route-generator.ts` → 已迁移到 `packages/tools/src/utils/route-generator.ts`
### 新增的文件
- `packages/tools/src/vite-plugins/auto-routes.ts`
- `packages/tools/src/utils/route-generator.ts`
- `packages/tools/README.md`
## 使用方式
使用方式保持不变,只需更新导入路径即可。所有配置选项和功能保持一致。
## 优势
1. **统一管理**:所有项目都可以使用同一个插件
2. **易于维护**:插件更新只需在一个地方进行
3. **版本控制**:通过包版本管理插件更新
4. **类型安全**:完整的 TypeScript 类型支持
# 自动路由生成功能
## 快速开始
本功能已集成到项目中,启动开发服务器时会自动扫描 `src/views` 目录并生成路由。
> **注意**:插件已迁移到 `@venus/tools` 包中统一管理,所有项目都可以通过配置使用。
### 使用步骤
1. **创建页面文件**
```bash
# 在 src/views 目录下创建新的 Vue 文件
touch src/views/NewPage.vue
```
2. **自动生成路由**
- 开发模式下,文件变化时会自动重新生成路由
- 路由文件位置:`src/router/auto-routes.ts`
3. **访问页面**
- 路由路径:`/new-page`
- 路由名称:`NewPage`
## 配置说明
### 基本配置
在 `vite.config.ts` 中已配置:
```typescript
autoRoutes({
viewsDir: 'src/views', // views 目录
outputFile: 'src/router/auto-routes.ts', // 输出文件
exclude: ['components', 'NotFound.vue'], // 排除文件
watch: true, // 开发模式监听
})
```
### 自定义路由规则
在 `vite.config.ts` 的 `customRules` 中配置:
```typescript
customRules: (filePath, routeConfig) => {
// 自定义路由配置
if (filePath.includes('SpecialPage.vue')) {
return {
...routeConfig,
path: '/custom-path',
name: 'CustomName',
title: '自定义标题',
};
}
return routeConfig;
}
```
## 路由生成规则
| 文件路径 | 路由路径 | 路由名称 |
|---------|---------|---------|
| `views/User.vue` | `/user` | `User` |
| `views/ManageKonw/index.vue` | `/managekonw` | `ManageKonw` |
| `views/Assistant/addUpdate.vue` | `/assistant/add-update` | `AssistantAddUpdate` |
## 手动配置路由
如需手动配置特殊路由,在 `src/router/index.ts` 的 `manualRoutes` 中添加:
```typescript
const manualRoutes: RouteRecordRaw[] = [
{
path: '/custom',
name: 'Custom',
component: () => import('@/views/Custom.vue'),
meta: { title: '自定义路由' },
},
];
```
## 详细文档
查看完整文档:[docs/auto-routes.md](./docs/auto-routes.md)
## 注意事项
- ⚠️ **不要手动编辑** `src/router/auto-routes.ts`,此文件由插件自动生成
- ✅ 自定义路由请在 `vite.config.ts` 的 `customRules` 中配置
- ✅ 特殊路由请在 `router/index.ts` 的 `manualRoutes` 中添加
# 自动路由生成功能
## 概述
自动路由生成功能可以根据 `views` 目录中的文件结构自动生成 Vue Router 路由配置,无需手动维护路由文件。
## 功能特性
- ✅ **自动扫描**:自动扫描 `src/views` 目录下的所有 Vue 文件
- ✅ **智能转换**:自动将文件路径转换为路由路径和路由名称
- ✅ **热更新**:开发模式下,文件变化时自动重新生成路由
- ✅ **灵活配置**:支持自定义路由规则、排除文件、路由前缀等
- ✅ **类型安全**:生成的路由文件包含完整的 TypeScript 类型
## 路由生成规则
### 基本规则
1. **文件路径 → 路由路径**
- `views/User.vue` → `/user`
- `views/ManageKonw/index.vue` → `/managekonw`
- `views/Assistant/addUpdate.vue` → `/assistant/add-update`
2. **文件路径 → 路由名称**
- `views/User.vue` → `User`
- `views/ManageKonw/index.vue` → `ManageKonw`
- `views/Assistant/addUpdate.vue` → `AssistantAddUpdate`
3. **文件路径 → 路由标题**
- `views/User.vue` → `User`
- `views/ManageKonw/index.vue` → `ManageKonw`
### 特殊处理
- **index.vue**:如果文件名是 `index.vue`,路由路径使用目录名
- **PascalCase 转换**:自动将 PascalCase 文件名转换为 kebab-case 路由路径
- **排除规则**:默认排除 `components` 目录和 `NotFound.vue` 文件
## 配置方式
### 在 vite.config.ts 中配置
```typescript
import { autoRoutes } from '@venus/tools/src/vite-plugins/auto-routes';
export default defineConfig({
plugins: [
autoRoutes({
// views 目录路径(相对于项目根目录)
viewsDir: 'src/views',
// 生成的路由文件路径
outputFile: 'src/router/auto-routes.ts',
// 路由前缀(所有路由都会加上这个前缀)
routePrefix: '',
// 排除的文件或目录
exclude: ['components', 'components/', 'NotFound.vue'],
// 是否在开发模式下监听文件变化
watch: true,
// 自定义路由规则
customRules: (filePath, routeConfig) => {
// 示例:为特定文件自定义路由配置
if (filePath.includes('Assistant/addUpdate.vue')) {
return {
...routeConfig,
path: '/assistant/add',
name: 'AssistantAdd',
title: '新增智能体',
};
}
// 示例:跳过某些文件
if (filePath.includes('Test.vue')) {
return null; // 返回 null 表示跳过此路由
}
return routeConfig;
},
}),
// ... 其他插件
],
});
```
### 自定义路由规则示例
#### 1. 自定义路由路径和名称
```typescript
customRules: (filePath, routeConfig) => {
if (filePath.includes('UserProfile.vue')) {
return {
...routeConfig,
path: '/profile',
name: 'UserProfile',
title: '个人资料',
};
}
return routeConfig;
}
```
#### 2. 添加路由元数据
```typescript
customRules: (filePath, routeConfig) => {
if (filePath.includes('Admin')) {
return {
...routeConfig,
meta: {
...routeConfig.meta,
requiresAuth: true,
roles: ['admin'],
hideInMenu: false,
},
};
}
return routeConfig;
}
```
#### 3. 跳过某些文件
```typescript
customRules: (filePath, routeConfig) => {
// 跳过测试文件
if (filePath.includes('.test.') || filePath.includes('.spec.')) {
return null;
}
return routeConfig;
}
```
#### 4. 处理动态路由
```typescript
customRules: (filePath, routeConfig) => {
// 将 [id].vue 转换为动态路由
if (filePath.includes('[id].vue')) {
return {
...routeConfig,
path: routeConfig.path?.replace('[id]', ':id'),
};
}
return routeConfig;
}
```
## 使用方式
### 1. 创建新页面
在 `src/views` 目录下创建新的 Vue 文件:
```bash
# 创建新页面
touch src/views/NewPage.vue
```
路由会自动生成:
- 路径:`/new-page`
- 名称:`NewPage`
- 标题:`NewPage`
### 2. 创建嵌套页面
```bash
# 创建嵌套目录和页面
mkdir -p src/views/Product
touch src/views/Product/index.vue
touch src/views/Product/Detail.vue
```
路由会自动生成:
- `/product` → `Product/index.vue`
- `/product/detail` → `Product/Detail.vue`
### 3. 手动覆盖路由
如果需要手动配置某些路由,可以在 `src/router/index.ts` 中的 `manualRoutes` 数组中添加:
```typescript
const manualRoutes: RouteRecordRaw[] = [
{
path: '/custom',
name: 'Custom',
component: () => import('@/views/Custom.vue'),
meta: {
title: '自定义路由',
},
},
];
```
手动配置的路由优先级更高,会覆盖自动生成的路由。
## 生成的路由文件
自动生成的路由文件位于 `src/router/auto-routes.ts`,内容示例:
```typescript
// 此文件由 auto-routes 插件自动生成,请勿手动编辑
// 生成时间: 2024-01-01 12:00:00
import type { RouteRecordRaw } from 'vue-router';
export const autoRoutes: RouteRecordRaw[] = [
{
path: '/',
name: 'Home',
component: () => import('@/views/Home.vue'),
meta: {
title: 'Home',
},
},
{
path: '/user',
name: 'User',
component: () => import('@/views/User.vue'),
meta: {
title: 'User',
},
},
// ... 更多路由
];
```
**注意**:此文件是自动生成的,请勿手动编辑。如需自定义路由,请使用 `customRules` 配置或在 `manualRoutes` 中添加。
## 开发模式
在开发模式下,插件会监听 `views` 目录的变化:
- **文件新增**:自动生成新路由
- **文件删除**:自动移除对应路由
- **文件修改**:触发路由重新生成和热更新
## 构建模式
在构建模式下,插件会在构建开始时生成路由文件,确保生产环境使用最新的路由配置。
## 常见问题
### Q: 如何排除某些文件不生成路由?
A: 在配置中使用 `exclude` 选项:
```typescript
exclude: ['components', 'components/', 'Test.vue', /\.test\.vue$/]
```
### Q: 如何自定义路由路径?
A: 使用 `customRules` 配置:
```typescript
customRules: (filePath, routeConfig) => {
if (filePath.includes('MyPage.vue')) {
return {
...routeConfig,
path: '/my-custom-path',
};
}
return routeConfig;
}
```
### Q: 生成的路由文件在哪里?
A: 默认在 `src/router/auto-routes.ts`,可以通过 `outputFile` 选项自定义。
### Q: 如何禁用自动路由生成?
A: 从 `vite.config.ts` 的 `plugins` 数组中移除 `autoRoutes()` 插件即可。
## 最佳实践
1. **使用约定式命名**:遵循 Vue 文件命名规范(PascalCase),便于自动转换
2. **合理使用排除规则**:排除不需要生成路由的文件(如组件、测试文件等)
3. **自定义特殊路由**:对于需要特殊配置的路由(如动态路由、权限控制),使用 `customRules` 或 `manualRoutes`
4. **保持文件结构清晰**:合理的目录结构有助于生成清晰的路由结构
## 技术实现
- **Vite 插件**:使用 Vite 插件 API 实现文件监听和代码生成
- **文件系统扫描**:递归扫描 `views` 目录,识别 Vue 文件
- **路径转换算法**:将文件路径转换为符合 Vue Router 规范的路由配置
- **热更新支持**:集成 Vite 的 HMR 机制,实现开发时的自动更新
...@@ -15,6 +15,19 @@ ...@@ -15,6 +15,19 @@
"import": "./dist/index.esm.js", "import": "./dist/index.esm.js",
"require": "./dist/index.cjs.js" "require": "./dist/index.cjs.js"
}, },
"./vite-plugins/auto-routes": {
"types": "./dist/vite-plugins/auto-routes.d.ts",
"import": "./dist/vite-plugins/auto-routes.esm.js",
"require": "./dist/vite-plugins/auto-routes.cjs.js"
},
"./src/vite-plugins/auto-routes": {
"types": "./src/vite-plugins/auto-routes.ts",
"import": "./src/vite-plugins/auto-routes.ts"
},
"./src/utils/route-generator": {
"types": "./src/utils/route-generator.ts",
"import": "./src/utils/route-generator.ts"
},
"./dist/*": "./dist/*" "./dist/*": "./dist/*"
}, },
"buildOptions": { "buildOptions": {
...@@ -23,5 +36,17 @@ ...@@ -23,5 +36,17 @@
"esm", "esm",
"cjs" "cjs"
] ]
},
"peerDependencies": {
"vite": "^5.0.0",
"vue-router": "^4.0.0"
},
"peerDependenciesMeta": {
"vite": {
"optional": false
},
"vue-router": {
"optional": false
}
} }
} }
...@@ -6,3 +6,11 @@ export function noop(): void {} ...@@ -6,3 +6,11 @@ export function noop(): void {}
export function sum(a: number, b: number): number { export function sum(a: number, b: number): number {
return a + b; return a + b;
} }
// 导出自动路由生成插件
export { autoRoutes } from "./vite-plugins/auto-routes";
export type { AutoRoutesOptions } from "./vite-plugins/auto-routes";
// 导出路由生成工具
export { generateRoutes, loadRouteConfig } from "./utils/route-generator";
export type { RouteConfig, RouteGeneratorOptions } from "./utils/route-generator";
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",
});
}
},
};
}
...@@ -586,6 +586,9 @@ importers: ...@@ -586,6 +586,9 @@ importers:
'@venus/tailwind-config': '@venus/tailwind-config':
specifier: workspace:* specifier: workspace:*
version: link:../../../../internal/tailwind-config version: link:../../../../internal/tailwind-config
'@venus/tools':
specifier: workspace:*
version: link:../../../../packages/tools
'@vue-office/docx': '@vue-office/docx':
specifier: 'catalog:' specifier: 'catalog:'
version: 1.6.3(vue-demi@0.14.10(vue@3.5.26(typescript@5.9.3)))(vue@3.5.26(typescript@5.9.3)) version: 1.6.3(vue-demi@0.14.10(vue@3.5.26(typescript@5.9.3)))(vue@3.5.26(typescript@5.9.3))
...@@ -1202,7 +1205,14 @@ importers: ...@@ -1202,7 +1205,14 @@ importers:
specifier: 'catalog:' specifier: 'catalog:'
version: 4.6.4(vue@3.5.26(typescript@5.9.3)) version: 4.6.4(vue@3.5.26(typescript@5.9.3))
packages/tools: {} packages/tools:
dependencies:
vite:
specifier: ^7.1.2
version: 7.3.1(@types/node@24.10.4)(jiti@2.6.1)(sass@1.97.2)(terser@5.44.1)(yaml@2.8.2)
vue-router:
specifier: ^4.0.0
version: 4.6.4(vue@3.5.26(typescript@5.9.3))
packages/types: packages/types:
dependencies: dependencies:
...@@ -10015,7 +10025,6 @@ packages: ...@@ -10015,7 +10025,6 @@ packages:
vue-i18n@9.14.5: vue-i18n@9.14.5:
resolution: {integrity: sha512-0jQ9Em3ymWngyiIkj0+c/k7WgaPO+TNzjKSNq9BvBQaKJECqn9cd9fL4tkDhB5G1QBskGl9YxxbDAhgbFtpe2g==} resolution: {integrity: sha512-0jQ9Em3ymWngyiIkj0+c/k7WgaPO+TNzjKSNq9BvBQaKJECqn9cd9fL4tkDhB5G1QBskGl9YxxbDAhgbFtpe2g==}
engines: {node: '>= 16'} engines: {node: '>= 16'}
deprecated: v9 and v10 no longer supported. please migrate to v11. about maintenance status, see https://vue-i18n.intlify.dev/guide/maintenance.html
peerDependencies: peerDependencies:
vue: ^3.5.17 vue: ^3.5.17
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!