Commit 4947e631 by Lin

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

1 parent 6dd252f3
{
"name": "@venus/venus-agentic-assisant",
"version": "1.0.0",
"description": "Vue3 微前端子应用模板,用于与 qiankun 基座集成",
"description": "汽车智能体-智能助理",
"private": true,
"type": "module",
"scripts": {
......@@ -12,25 +12,26 @@
"type-check": "vue-tsc --noEmit"
},
"dependencies": {
"@vue-office/docx": "catalog:",
"@vue-office/pdf": "catalog:",
"@vue-office/excel": "catalog:",
"@element-plus/icons-vue": "catalog:",
"@js-preview/docx": "catalog:",
"@js-preview/excel": "catalog:",
"@vue-office/pptx": "catalog:",
"@js-preview/pdf": "catalog:",
"@js-preview/docx": "catalog:",
"@element-plus/icons-vue": "catalog:",
"@venus/tailwind-config": "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:",
"axios": "catalog:",
"element-plus": "catalog:",
"glsk-oss-jssdk": "catalog:",
"pinia": "catalog:",
"sass": "catalog:",
"tailwindcss": "catalog:",
"vue": "catalog:",
"vue-router": "catalog:",
"glsk-oss-jssdk": "catalog:",
"sass": "catalog:"
"vue-router": "catalog:"
},
"devDependencies": {
......
<script setup lang="ts">
import { onMounted } from 'vue';
import { onMounted } from "vue";
onMounted(() => {
// console.log('Vue3 微应用已挂载');
// console.log('Vue3 微应用已挂载');
});
</script>
<template>
<main class="app-main">
<router-view v-slot="{ Component }">
<transition name="fade" mode="out-in">
<component :is="Component" />
</transition>
</router-view>
</main>
<main class="app-main">
<router-view v-slot="{ Component }">
<transition mode="out-in" name="fade">
<component :is="Component" />
</transition>
</router-view>
</main>
</template>
<style scoped>
......
// 此文件由 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,84 +2,124 @@ import type { Router, RouteRecordRaw } from 'vue-router';
import { createRouter as _createRouter, createWebHistory } from 'vue-router';
const routes: RouteRecordRaw[] = [
{
path: '/',
name: 'Home',
component: () => import('@/views/Home.vue'),
meta: {
title: '首页',
// 导入自动生成的路由
// 注意:使用动态导入以避免构建时错误
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: '/',
name: 'Home',
component: () => import('@/views/Home.vue'),
meta: {
title: '首页',
},
},
},
{
path: '/managekonw',
name: 'ManageKonw',
component: () => import('@/views/ManageKonw/index.vue'),
meta: {
title: '知识管理',
{
path: '/managekonw',
name: 'ManageKonw',
component: () => import('@/views/ManageKonw/index.vue'),
meta: {
title: '知识管理',
},
},
},
{
path: '/assistant',
name: 'Assistant',
component: () => import('@/views/Assistant/index.vue'),
meta: {
title: '岗位助理配置',
{
path: '/assistant',
name: 'Assistant',
component: () => import('@/views/Assistant/index.vue'),
meta: {
title: '岗位助理配置',
},
},
},
{
path: '/manageagentic',
name: 'ManageAgentic',
component: () => import('@/views/ManageAgentic/index.vue'),
meta: {
title: '智能体管理',
{
path: '/manageagentic',
name: 'ManageAgentic',
component: () => import('@/views/ManageAgentic/index.vue'),
meta: {
title: '智能体管理',
},
},
},
{
path: '/assistant/add',
name: 'AssistantAdd',
component: () => import('@/views/Assistant/addUpdate.vue'),
meta: {
title: '新增智能体',
{
path: '/assistant/add',
name: 'AssistantAdd',
component: () => import('@/views/Assistant/addUpdate.vue'),
meta: {
title: '新增智能体',
},
},
},
{
path: '/assistant/edit/:id',
name: 'AssistantEdit',
component: () => import('@/views/Assistant/addUpdate.vue'),
meta: {
title: '编辑',
{
path: '/assistant/edit/:id',
name: 'AssistantEdit',
component: () => import('@/views/Assistant/addUpdate.vue'),
meta: {
title: '编辑',
},
},
},
{
path: '/user',
name: 'User',
component: () => import('@/views/User.vue'),
meta: {
title: '用户管理',
{
path: '/user',
name: 'User',
component: () => import('@/views/User.vue'),
meta: {
title: '用户管理',
},
},
},
{
path: '/settings',
name: 'Settings',
component: () => import('@/views/Settings.vue'),
meta: {
title: '系统设置',
{
path: '/settings',
name: 'Settings',
component: () => import('@/views/Settings.vue'),
meta: {
title: '系统设置',
},
},
},
{
path: '/communication',
name: 'Communication',
component: () => import('@/views/Communication.vue'),
meta: {
title: '通信示例',
{
path: '/communication',
name: 'Communication',
component: () => import('@/views/Communication.vue'),
meta: {
title: '通信示例',
},
},
},
{
path: '/:pathMatch(.*)*',
name: 'NotFound',
component: () => import('@/views/NotFound.vue'),
},
{
path: '/:pathMatch(.*)*',
name: 'NotFound',
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 @@
"composite": true,
"module": "ESNext",
"moduleResolution": "bundler",
"paths": {
"@venus/tools/*": ["../../../../packages/tools/src/*"]
},
"allowSyntheticDefaultImports": true,
"skipLibCheck": true
},
"include": ["vite.config.ts"]
"include": ["vite.config.ts", "vite-plugins/**/*.ts"]
}
# @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 @@
"import": "./dist/index.esm.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/*"
},
"buildOptions": {
......@@ -23,5 +36,17 @@
"esm",
"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 {}
export function sum(a: number, b: number): number {
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:
'@venus/tailwind-config':
specifier: workspace:*
version: link:../../../../internal/tailwind-config
'@venus/tools':
specifier: workspace:*
version: link:../../../../packages/tools
'@vue-office/docx':
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))
......@@ -1202,7 +1205,14 @@ importers:
specifier: 'catalog:'
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:
dependencies:
......@@ -10015,7 +10025,6 @@ packages:
vue-i18n@9.14.5:
resolution: {integrity: sha512-0jQ9Em3ymWngyiIkj0+c/k7WgaPO+TNzjKSNq9BvBQaKJECqn9cd9fL4tkDhB5G1QBskGl9YxxbDAhgbFtpe2g==}
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:
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!