befly-admin 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/.env.development +4 -0
  2. package/.env.production +4 -0
  3. package/LICENSE +201 -0
  4. package/README.md +143 -0
  5. package/index.html +13 -0
  6. package/libs/auto-routes-template.js +104 -0
  7. package/libs/autoRouter.ts +67 -0
  8. package/libs/icons.ts +543 -0
  9. package/package.json +42 -0
  10. package/public/logo.svg +106 -0
  11. package/src/App.vue +17 -0
  12. package/src/api/auth.ts +60 -0
  13. package/src/components/Icon.vue +41 -0
  14. package/src/env.d.ts +9 -0
  15. package/src/layouts/0.vue +207 -0
  16. package/src/layouts/1.vue +22 -0
  17. package/src/layouts/2.vue +166 -0
  18. package/src/main.ts +19 -0
  19. package/src/plugins/http.ts +94 -0
  20. package/src/plugins/router.ts +47 -0
  21. package/src/plugins/store.ts +19 -0
  22. package/src/styles/index.scss +198 -0
  23. package/src/styles/mixins.scss +98 -0
  24. package/src/styles/variables.scss +75 -0
  25. package/src/types/env.d.ts +23 -0
  26. package/src/util.ts +28 -0
  27. package/src/views/403/403.vue +33 -0
  28. package/src/views/admin/components/edit.vue +147 -0
  29. package/src/views/admin/components/role.vue +135 -0
  30. package/src/views/admin/index.vue +169 -0
  31. package/src/views/dict/components/edit.vue +156 -0
  32. package/src/views/dict/index.vue +159 -0
  33. package/src/views/index/components/AddonList.vue +125 -0
  34. package/src/views/index/components/EnvironmentInfo.vue +97 -0
  35. package/src/views/index/components/OperationLogs.vue +112 -0
  36. package/src/views/index/components/PerformanceMetrics.vue +148 -0
  37. package/src/views/index/components/QuickActions.vue +27 -0
  38. package/src/views/index/components/ServiceStatus.vue +193 -0
  39. package/src/views/index/components/SystemNotifications.vue +136 -0
  40. package/src/views/index/components/SystemOverview.vue +188 -0
  41. package/src/views/index/components/SystemResources.vue +104 -0
  42. package/src/views/index/components/UserInfo.vue +136 -0
  43. package/src/views/index/index.vue +62 -0
  44. package/src/views/login/index_1.vue +694 -0
  45. package/src/views/menu/components/edit.vue +150 -0
  46. package/src/views/menu/index.vue +168 -0
  47. package/src/views/news/detail/detail_2.vue +26 -0
  48. package/src/views/news/detail/index.vue +26 -0
  49. package/src/views/news/news.vue +26 -0
  50. package/src/views/role/components/api.vue +280 -0
  51. package/src/views/role/components/edit.vue +129 -0
  52. package/src/views/role/components/menu.vue +143 -0
  53. package/src/views/role/index.vue +179 -0
  54. package/src/views/user/user.vue +320 -0
  55. package/temp/router.js +71 -0
  56. package/tsconfig.json +34 -0
  57. package/vite.config.ts +100 -0
@@ -0,0 +1,4 @@
1
+ # 开发环境配置
2
+
3
+ # 接口请求地址
4
+ VITE_API_BASE_URL=http://localhost:3000/api
@@ -0,0 +1,4 @@
1
+ # 生产环境配置
2
+
3
+ # 接口请求地址(部署时修改为实际的生产环境地址)
4
+ VITE_API_BASE_URL=https://api.your-domain.com/api
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,143 @@
1
+ # Befly Admin
2
+
3
+ 基于 Vue3 + TDesign Vue Next + TypeScript + Vite 的后台管理系统。
4
+
5
+ ## 技术栈
6
+
7
+ - **Vue 3** - 渐进式 JavaScript 框架
8
+ - **TDesign Vue Next** - 企业级设计体系
9
+ - **TypeScript** - 类型安全
10
+ - **Vite** - 下一代前端构建工具
11
+ - **SCSS** - CSS 预处理器
12
+ - **Vue Router** - 路由管理
13
+ - **Pinia** - 状态管理
14
+ - **unplugin-auto-import** - API 自动导入
15
+ - **unplugin-vue-components** - 组件自动导入
16
+
17
+ ## 特性
18
+
19
+ - ✅ 自动导入 Vue3 API(ref、reactive、computed 等)
20
+ - ✅ 自动导入 TDesign 组件(无需手动注册)
21
+ - ✅ 自动导入 Vue Router 和 Pinia API
22
+ - ✅ TypeScript 类型安全
23
+ - ✅ SCSS 支持(全局变量 + Mixins)
24
+ - ✅ 响应式布局
25
+ - ✅ 路由权限控制
26
+ - ✅ 代理配置(开发环境)
27
+
28
+ ## 开发
29
+
30
+ ```bash
31
+ # 安装依赖
32
+ bun install
33
+
34
+ # 启动开发服务器
35
+ bun run dev
36
+
37
+ # 构建生产版本
38
+ bun run build
39
+
40
+ # 预览生产版本
41
+ bun run preview
42
+
43
+ # 类型检查
44
+ bun run type-check
45
+ ```
46
+
47
+ ## 项目结构
48
+
49
+ ```
50
+ admin/
51
+ ├── src/
52
+ │ ├── layouts/ # 布局组件
53
+ │ ├── views/ # 页面组件
54
+ │ │ ├── login/ # 登录页
55
+ │ │ └── dashboard/ # 仪表盘
56
+ │ ├── router/ # 路由配置
57
+ │ ├── styles/ # 全局样式
58
+ │ ├── types/ # 类型定义
59
+ │ ├── App.vue # 根组件
60
+ │ └── main.ts # 入口文件
61
+ ├── index.html
62
+ ├── vite.config.ts # Vite 配置
63
+ ├── tsconfig.json # TypeScript 配置
64
+ └── package.json
65
+ ```
66
+
67
+ ## 自动导入说明
68
+
69
+ ### API 自动导入
70
+
71
+ 无需手动导入以下 API,直接使用即可:
72
+
73
+ ```typescript
74
+ // ❌ 不需要这样写
75
+ import { ref, computed, onMounted } from 'vue';
76
+ import { useRouter, useRoute } from 'vue-router';
77
+ import { defineStore } from 'pinia';
78
+
79
+ // ✅ 直接使用
80
+ const count = ref(0);
81
+ const router = useRouter();
82
+ const store = defineStore('main', {});
83
+ ```
84
+
85
+ ### 组件自动导入
86
+
87
+ TDesign 组件无需手动导入和注册:
88
+
89
+ ```vue
90
+ <template>
91
+ <!-- ✅ 直接使用,无需导入 -->
92
+ <t-button>按钮</t-button>
93
+ <t-input v-model="value" />
94
+ <t-table :data="tableData" />
95
+ </template>
96
+
97
+ <script setup lang="ts">
98
+ // ❌ 不需要这样写
99
+ // import { Button, Input, Table } from 'tdesign-vue-next';
100
+ </script>
101
+ ```
102
+
103
+ ## 配置说明
104
+
105
+ ### Vite 配置
106
+
107
+ - **自动导入配置**: `unplugin-auto-import` 和 `unplugin-vue-components`
108
+ - **路径别名**: `@` 指向 `src` 目录
109
+ - **开发服务器**: 端口 5173,自动打开浏览器
110
+ - **代理配置**: `/api` 代理到 `http://localhost:3000`
111
+
112
+ ### TypeScript 配置
113
+
114
+ - **严格模式**: 启用所有严格类型检查
115
+ - **路径映射**: `@/*` 映射到 `src/*`
116
+ - **自动生成类型**: `auto-imports.d.ts` 和 `components.d.ts`
117
+
118
+ ## 构建
119
+
120
+ ```bash
121
+ # 构建生产版本
122
+ bun run build
123
+
124
+ # 输出目录:dist/
125
+ ```
126
+
127
+ 构建优化:
128
+
129
+ - 代码分割(Vue、TDesign 单独打包)
130
+ - Tree-shaking
131
+ - 压缩优化
132
+ - Chunk size 限制:1500KB
133
+
134
+ ## 注意事项
135
+
136
+ 1. **自动导入的类型定义**:首次运行会生成 `src/types/auto-imports.d.ts` 和 `components.d.ts`
137
+ 2. **登录功能**:当前为模拟登录,需要对接真实 API
138
+ 3. **Token 存储**:使用 localStorage,生产环境建议使用更安全的方式
139
+ 4. **API 代理**:开发环境 `/api` 代理到 `http://localhost:3000`
140
+
141
+ ## License
142
+
143
+ Apache-2.0
package/index.html ADDED
@@ -0,0 +1,13 @@
1
+ <!DOCTYPE html>
2
+ <html lang="zh-CN">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <link rel="icon" type="image/svg+xml" href="/vite.svg" />
6
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7
+ <title>Befly Admin - 后台管理系统</title>
8
+ </head>
9
+ <body>
10
+ <div id="app"></div>
11
+ <script type="module" src="/src/main.ts"></script>
12
+ </body>
13
+ </html>
@@ -0,0 +1,104 @@
1
+ // 模板文件:自动路由生成结果基模板
2
+ // 说明:
3
+ // 目录固定:src/views ;布局目录固定:src/layouts
4
+ // 仅识别 views/<name>/<name>.vue 结构;index 为根路径
5
+ // 固定排除子目录:components
6
+ // 不区分公开/私有路由,全部挂到对应布局(文件名后缀 *_n.vue 指定布局 n,默认 0)
7
+
8
+ // 在虚拟模块环境中,统一使用绝对形式 '/src/...'
9
+ // 支持多级目录:新规则
10
+ // 1. 任意目录下的 index.vue 代表该目录的“默认路由”,不再附加文件段:/news/index.vue -> /news
11
+ // 2. 非 index.vue 页面,路径 = 所有目录段 + 文件名:/news/detail/detail.vue -> /news/detail/detail
12
+ // 即使文件名与末级目录同名亦需保留(区别于旧规则会省略重复)
13
+ // 3. 根目录 index.vue -> '/'
14
+ // 4. 布局后缀规则:只允许出现在“页面文件名”末尾:<name>_n.vue;目录名不再解析布局编号
15
+ // 5. 任何层级的 components 子目录下文件忽略
16
+ // 6. 大小写驼峰与下划线会被 kebab 化
17
+ // 示例:
18
+ // /src/views/news/index.vue => /news
19
+ // /src/views/news/detail/detail.vue => /news/detail/detail
20
+ // /src/views/user/profile/index.vue => /user/profile
21
+ // /src/views/user/profile/edit.vue => /user/profile/edit
22
+ // /src/views/index.vue => /
23
+ // /src/views/dashboard_2/index.vue => /dashboard (布局2)
24
+ // /src/views/dashboard_2/analysis.vue => /dashboard/analysis (布局2)
25
+ const viewFiles = import.meta.glob('/src/views/**/*.vue');
26
+ const layoutFiles = import.meta.glob('/src/layouts/*.vue');
27
+
28
+ const layoutRoutes = {};
29
+
30
+ function normalizePath(p) {
31
+ return p.replace(/\\/g, '/');
32
+ }
33
+ function extractLayoutFromFile(baseName) {
34
+ const m = baseName.match(/_(\d+)$/);
35
+ if (m) return { name: baseName.replace(/_(\d+)$/, ''), layout: m[1] };
36
+ return { name: baseName, layout: '0' };
37
+ }
38
+ function toKebab(s) {
39
+ return s
40
+ .replace(/([a-z])([A-Z])/g, '$1-$2') // camelCase -> camel-Case
41
+ .replace(/[\s_]+/g, '-') // 空白或下划线 -> -
42
+ .toLowerCase()
43
+ .replace(/-+/g, '-') // 合并多余 -
44
+ .replace(/^|-$/g, ''); // 去首尾 -
45
+ }
46
+ function buildPath(name) {
47
+ return name === 'index' ? '/' : '/' + toKebab(name);
48
+ }
49
+ function buildName(name) {
50
+ return toKebab(name);
51
+ }
52
+ // 不再区分公开路由,全部放入对应布局
53
+
54
+ for (const fp in viewFiles) {
55
+ const normPath = normalizePath(fp);
56
+ if (!normPath.endsWith('.vue')) continue;
57
+ if (normPath.includes('/components/')) continue;
58
+ const rootMarker = '/src/views/';
59
+ const idx = normPath.indexOf(rootMarker);
60
+ if (idx === -1) continue;
61
+ const rel = normPath.slice(idx + rootMarker.length); // 相对 views 的路径
62
+ const parts = rel.split('/');
63
+ const fileName = parts.pop(); // <name>.vue 或 index.vue
64
+ if (!fileName) continue;
65
+ const rawBase = fileName.replace(/\.vue$/, '');
66
+ const { name: logicalBase, layout } = extractLayoutFromFile(rawBase);
67
+ const dirChainOriginal = parts; // 目录数组(可能为空)
68
+ if (dirChainOriginal.some((d) => d === 'components')) continue;
69
+ // 目录链直接使用原目录(不再剥离布局后缀)
70
+ const dirChainForPath = dirChainOriginal;
71
+ // index / index_n 作为目录默认:不追加文件名;非 index 保留
72
+ const pathSegments = [...dirChainForPath];
73
+ if (logicalBase !== 'index') pathSegments.push(logicalBase);
74
+ // root index 情况:views/index.vue => []
75
+ if (pathSegments.length === 1 && pathSegments[0] === 'index') pathSegments.pop();
76
+ // kebab 化
77
+ const kebabSegments = pathSegments.map(toKebab).filter(Boolean);
78
+ const routePath = '/' + kebabSegments.join('/');
79
+ const routeName = kebabSegments.length ? kebabSegments.join('-') : 'index';
80
+ const route = { path: routePath === '/' ? '/' : routePath, name: routeName, component: viewFiles[fp], meta: { title: routeName, file: fp } };
81
+ if (!layoutRoutes[layout]) layoutRoutes[layout] = [];
82
+ if (!layoutRoutes[layout].some((r) => r.path === route.path)) layoutRoutes[layout].push(route);
83
+ }
84
+ const finalRoutes = [];
85
+ for (const k in layoutRoutes) {
86
+ const lp = '/src/layouts/' + k + '.vue';
87
+ const comp = layoutFiles[lp];
88
+ if (comp) {
89
+ finalRoutes.push({ path: '/', name: 'layout' + k, component: comp, children: layoutRoutes[k] });
90
+ }
91
+ }
92
+ // 开发环境下在浏览器控制台打印一次路由结果
93
+ if (typeof window !== 'undefined' && import.meta && import.meta.env && import.meta.env.DEV) {
94
+ // 使用 setTimeout 避免与其他插件初始化竞争
95
+ setTimeout(() => {
96
+ // eslint-disable-next-line no-console
97
+ console.log(
98
+ '[auto-routes] 当前生成路由:',
99
+ finalRoutes.map((r) => ({ layout: r.name, children: r.children?.map((c) => ({ path: c.path, name: c.name, file: c.meta?.file })) }))
100
+ );
101
+ }, 0);
102
+ }
103
+
104
+ export default finalRoutes;
@@ -0,0 +1,67 @@
1
+ import type { Plugin, HmrContext } from 'vite';
2
+ import { readFileSync } from 'fs';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { dirname, resolve } from 'path';
5
+
6
+ /**
7
+ * 自动路由生成插件
8
+ * 逻辑放在外部模板文件 `auto-routes-template.js` 中,通过占位符替换实现:
9
+ */
10
+ // 固定:视图目录 src/views;布局目录 src/layouts;排除目录 ['components'];不区分公开路由;模板已为最终可执行代码,不再做占位符替换。
11
+ export default function autoRouter(): Plugin {
12
+ const virtualModuleId = 'virtual:auto-routes';
13
+ const resolvedVirtualModuleId = '\0' + virtualModuleId;
14
+ // 目录固定,无需配置
15
+
16
+ // 模板路径:基于当前文件所在目录,避免 process.cwd() 导致嵌套 workspace 时的重复路径问题
17
+ const thisDir = dirname(fileURLToPath(import.meta.url));
18
+ const templatePath = resolve(thisDir, 'auto-routes-template.js');
19
+
20
+ // 缓存与状态
21
+ let cached = '';
22
+ let loadError = false;
23
+
24
+ function readTemplate() {
25
+ try {
26
+ const content = readFileSync(templatePath, 'utf-8');
27
+ cached = content;
28
+ loadError = false;
29
+ } catch (e) {
30
+ loadError = true;
31
+ cached = `console.error('[auto-routes] 模板读取失败: ${templatePath}');export default [];`;
32
+ }
33
+ }
34
+
35
+ // 初次读取
36
+ readTemplate();
37
+
38
+ return {
39
+ name: 'auto-router',
40
+ enforce: 'pre',
41
+ resolveId(id) {
42
+ if (id === virtualModuleId) return resolvedVirtualModuleId;
43
+ },
44
+ buildStart() {
45
+ // 监听模板文件
46
+ try {
47
+ this.addWatchFile(templatePath);
48
+ } catch {}
49
+ },
50
+ handleHotUpdate(ctx: HmrContext) {
51
+ if (ctx.file === templatePath) {
52
+ const before = cached;
53
+ readTemplate();
54
+ if (cached !== before) {
55
+ this.invalidate(resolvedVirtualModuleId);
56
+ }
57
+ }
58
+ },
59
+ load(id) {
60
+ if (id !== resolvedVirtualModuleId) return;
61
+ if (loadError || !cached) {
62
+ readTemplate();
63
+ }
64
+ return cached;
65
+ }
66
+ };
67
+ }