From 72cea2935da1272cb316c186e7018991be34f4a0 Mon Sep 17 00:00:00 2001 From: wangys <3401275564@qq.com> Date: Wed, 7 Jan 2026 15:30:29 +0800 Subject: [PATCH] =?UTF-8?q?web=E6=89=93=E5=8C=85=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../documents/修复平台应用空白页面问题.md | 144 ++++++++++++++++++ urbanLifelineWeb/.vscode/launch.json | 75 +++++++++ urbanLifelineWeb/packages/bidding/index.html | 2 +- .../bidding/public/app-config.local.js | 60 ++++++++ urbanLifelineWeb/packages/bidding/src/main.ts | 1 - .../bidding/src/router/dynamicRoute.ts | 38 +++-- .../packages/bidding/src/router/index.ts | 45 +++--- .../packages/bidding/vite.config.ts | 28 +++- urbanLifelineWeb/packages/platform/index.html | 2 +- .../platform/public/app-config.local.js | 60 ++++++++ .../packages/platform/src/main.ts | 57 +++---- .../platform/src/router/dynamicRoute.ts | 36 +++-- .../packages/platform/src/router/index.ts | 91 +++++++---- .../packages/platform/vite.config.ts | 29 +++- .../packages/shared/vite.config.ts | 10 ++ .../workcase/localSharedImportMap.js | 130 ---------------- urbanLifelineWeb/packages/workcase/index.html | 2 +- .../workcase/public/app-config.local.js | 65 ++++++++ .../packages/workcase/src/main.ts | 56 +++---- .../workcase/src/router/dynamicRoute.ts | 39 +++-- .../packages/workcase/src/router/index.ts | 88 ++++++----- .../packages/workcase/vite.config.ts | 39 +++-- 22 files changed, 762 insertions(+), 335 deletions(-) create mode 100644 urbanLifelineWeb/.trae/documents/修复平台应用空白页面问题.md create mode 100644 urbanLifelineWeb/packages/bidding/public/app-config.local.js create mode 100644 urbanLifelineWeb/packages/platform/public/app-config.local.js delete mode 100644 urbanLifelineWeb/packages/workcase/.__mf__temp/workcase/localSharedImportMap.js create mode 100644 urbanLifelineWeb/packages/workcase/public/app-config.local.js diff --git a/urbanLifelineWeb/.trae/documents/修复平台应用空白页面问题.md b/urbanLifelineWeb/.trae/documents/修复平台应用空白页面问题.md new file mode 100644 index 00000000..0f2a5bef --- /dev/null +++ b/urbanLifelineWeb/.trae/documents/修复平台应用空白页面问题.md @@ -0,0 +1,144 @@ +# 问题分析 + +根据用户提供的信息和代码检查,已经确定了导致平台应用在 build/preview 模式下出现空白页面的根本原因: + +## 1. 循环依赖死锁 + +平台应用的 `vue-vendor` chunk 中包含了顶层 `await`,用于等待 Module Federation 的 `loadShare` 完成: +```javascript +const Z=await X.then(e=>e()); // 等待 vue +const Pe=await Ee.then(e=>e()); // 等待 vue-router +``` + +这导致了以下循环依赖: +1. `vue-vendor` 加载时,执行顶层 `await`,等待 `loadShare` 完成 +2. `loadShare` 需要初始化 Module Federation +3. Module Federation 初始化又依赖 `vue-vendor` 文件 +4. 形成循环依赖死锁,整个应用初始化被阻塞 + +## 2. 配置问题 + +从配置文件可以看到: +- 平台模块的 `vite.config.ts` 中,`shared` 配置包含了 `vue` 和 `vue-router` +- 共享模块的 `vite.config.ts` 中,`shared` 配置也包含了 `vue` 和 `vue-router` +- 平台模块的 `manualChunks` 将 `vue` 和 `vue-router` 打包到了 `vue-vendor` chunk 中 + +# 解决方案 + +## 1. 修改平台模块的 Vite 配置 + +### 1.1 移除 shared 配置中的 vue 和 vue-router + +从平台模块的 `shared` 配置中移除 `vue` 和 `vue-router`,避免 Module Federation 尝试共享这些核心依赖。 + +```typescript +// packages/platform/vite.config.ts +federation({ + name: 'platform', + remotes: { + shared: { + type: 'module', + name: 'shared', + entry: sharedEntry + } + }, + shared: { + // 移除 vue 和 vue-router,避免循环依赖 + // vue: {}, + // 'vue-router': {}, + 'element-plus': {}, + axios: {} + } +}) +``` + +### 1.2 调整 manualChunks 配置 + +保持 `manualChunks` 配置不变,继续将 `vue` 和 `vue-router` 打包到 `vue-vendor` chunk 中,但不再尝试通过 Module Federation 共享它们。 + +## 2. 修改共享模块的 Vite 配置 + +### 2.1 移除 shared 配置中的 vue 和 vue-router + +从共享模块的 `shared` 配置中移除 `vue` 和 `vue-router`,避免 Module Federation 尝试共享这些核心依赖。 + +```typescript +// packages/shared/vite.config.ts +federation({ + name: 'shared', + filename: 'remoteEntry.js', + exposes: { + // ... 暴露的模块 + }, + shared: { + // 移除 vue 和 vue-router,避免循环依赖 + // vue: {}, + // 'vue-router': {}, + 'element-plus': {}, + 'lucide-vue-next': {}, + axios: {} + } +}) +``` + +## 3. 重新构建和测试 + +### 3.1 构建共享模块 + +```bash +# 切换到共享模块目录 +cd f:/Project/urbanLifeline/urbanLifelineWeb/packages/shared + +# 构建共享模块 +pnpm build +``` + +### 3.2 构建平台模块 + +```bash +# 切换到平台模块目录 +cd f:/Project/urbanLifeline/urbanLifelineWeb/packages/platform + +# 构建平台模块 +pnpm build + +# 启动预览服务器 +pnpm preview +``` + +### 3.3 验证应用是否正常运行 + +- 访问 `https://org.xyzh.yslg/platform/` +- 检查控制台是否显示 `✅ Platform 应用启动成功` 日志 +- 确认页面不再是空白,显示正常内容 + +# 预期结果 + +- 应用能够正常初始化,控制台显示 `✅ Platform 应用启动成功` 日志 +- 访问 `https://org.xyzh.yslg/platform/` 时显示正常内容,而不是空白页面 +- 所有依赖模块都能正确加载,没有循环依赖死锁 + +# 风险评估 + +- **依赖重复加载**:移除 `vue` 和 `vue-router` 从 `shared` 配置中可能导致这些依赖在多个模块中重复加载,但这是解决循环依赖死锁的必要代价 +- **构建错误**:需要确保修改后的配置能够正确构建 +- **运行时错误**:需要验证移除共享依赖后,应用是否能够正常运行 + +# 后续优化建议 + +1. **使用更稳定的 Module Federation 配置**:考虑使用 `@module-federation/runtime` 或其他更稳定的 Module Federation 实现 +2. **调整打包策略**:避免将核心依赖(如 `vue` 和 `vue-router`)与 Module Federation 相关代码打包到同一个 chunk 中 +3. **添加错误处理**:在应用初始化过程中添加错误处理,当依赖加载失败时给出明确提示 +4. **改进日志记录**:在应用初始化的关键节点添加更多日志,便于定位问题 + +# 执行步骤 + +1. **修改平台模块的 Vite 配置**:移除 `shared` 配置中的 `vue` 和 `vue-router` +2. **修改共享模块的 Vite 配置**:移除 `shared` 配置中的 `vue` 和 `vue-router` +3. **构建共享模块**:确保共享模块能够正确构建 +4. **构建平台模块**:确保平台模块能够正确构建 +5. **启动预览服务器**:启动平台模块的预览服务器 +6. **验证应用是否正常运行**:访问应用并验证是否正常运行 +7. **检查控制台输出**:确认控制台显示预期的日志 + +通过执行以上步骤,我们可以解决平台应用在 build/preview 模式下出现空白页面的问题,确保应用能够正常初始化和运行。 \ No newline at end of file diff --git a/urbanLifelineWeb/.vscode/launch.json b/urbanLifelineWeb/.vscode/launch.json index df833abc..5b544fc2 100644 --- a/urbanLifelineWeb/.vscode/launch.json +++ b/urbanLifelineWeb/.vscode/launch.json @@ -16,6 +16,21 @@ "clear": false } }, + { + "name": "预览 Shared 开发服务器", + "type": "node-terminal", + "request": "launch", + "command": "npm run preview", + "cwd": "${workspaceFolder}/packages/shared", + "presentation": { + "echo": true, + "reveal": "always", + "focus": false, + "panel": "new", + "showReuseMessage": true, + "clear": false + } + }, { "name": "启动 Platform 开发服务器", "type": "node-terminal", @@ -31,6 +46,21 @@ "clear": false } }, + { + "name": "预览 Platform 开发服务器", + "type": "node-terminal", + "request": "launch", + "command": "npm run preview", + "cwd": "${workspaceFolder}/packages/platform", + "presentation": { + "echo": true, + "reveal": "always", + "focus": false, + "panel": "new", + "showReuseMessage": true, + "clear": false + } + }, { "name": "启动 workcase 开发服务器", "type": "node-terminal", @@ -46,6 +76,21 @@ "clear": false } }, + { + "name": "预览 workcase 开发服务器", + "type": "node-terminal", + "request": "launch", + "command": "npm run preview", + "cwd": "${workspaceFolder}/packages/workcase", + "presentation": { + "echo": true, + "reveal": "always", + "focus": false, + "panel": "new", + "showReuseMessage": true, + "clear": false + } + }, { "name": "启动 Bidding 开发服务器", "type": "node-terminal", @@ -60,6 +105,21 @@ "showReuseMessage": true, "clear": false } + }, + { + "name": "预览 Bidding 开发服务器", + "type": "node-terminal", + "request": "launch", + "command": "npm run preview", + "cwd": "${workspaceFolder}/packages/bidding", + "presentation": { + "echo": true, + "reveal": "always", + "focus": false, + "panel": "new", + "showReuseMessage": true, + "clear": false + } } ], "compounds": [ @@ -77,6 +137,21 @@ "group": "", "order": 1 } + }, + { + "name": "启动所有预览 Web 项目", + "configurations": [ + "预览 Shared 开发服务器", + "预览 Platform 开发服务器", + "预览 workcase 开发服务器", + // "启动 Bidding 开发服务器" + ], + "stopAll": true, + "presentation": { + "hidden": false, + "group": "", + "order": 1 + } } ] } diff --git a/urbanLifelineWeb/packages/bidding/index.html b/urbanLifelineWeb/packages/bidding/index.html index 7a7c8d12..eb33f744 100644 --- a/urbanLifelineWeb/packages/bidding/index.html +++ b/urbanLifelineWeb/packages/bidding/index.html @@ -7,7 +7,7 @@ 招标管理系统 - + +
diff --git a/urbanLifelineWeb/packages/platform/public/app-config.local.js b/urbanLifelineWeb/packages/platform/public/app-config.local.js new file mode 100644 index 00000000..497a7286 --- /dev/null +++ b/urbanLifelineWeb/packages/platform/public/app-config.local.js @@ -0,0 +1,60 @@ +/** + * @description 本地开发环境配置文件 + * 用于 dev 和 preview 模式 + */ + +window.APP_RUNTIME_CONFIG = { + // 环境标识 + env: 'production', + + // API 配置 + api: { + baseUrl: 'https://org.xyzh.yslg/api', + timeout: 30000 + }, + + // 应用基础路径 + baseUrl: '/platform/', + + // 文件配置 + file: { + downloadUrl: 'https://org.xyzh.yslg/api/urban-lifeline/file/download/', + uploadUrl: 'https://org.xyzh.yslg/api/urban-lifeline/file/upload', + maxSize: { + image: 5, + video: 100, + document: 10 + }, + acceptTypes: { + image: 'image/*', + video: 'video/*', + document: '.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx' + } + }, + + // Token 配置 + token: { + key: 'token', + refreshThreshold: 300000 + }, + + // 公共资源路径 + publicImgPath: '/platform/img', + publicWebPath: '/platform', + + // 单点登录配置 + sso: { + platformUrl: 'https://org.xyzh.yslg/platform/', + workcaseUrl: 'https://org.xyzh.yslg/workcase/', + biddingUrl: 'https://org.xyzh.yslg/bidding/' + }, + + // AES 加密密钥(本地开发用,生产环境需要替换) + aesSecretKey: 'MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=', + + // 功能开关 + features: { + enableDebug: true, + enableMockData: false + } +}; diff --git a/urbanLifelineWeb/packages/platform/src/main.ts b/urbanLifelineWeb/packages/platform/src/main.ts index a25b1b37..e2b26825 100644 --- a/urbanLifelineWeb/packages/platform/src/main.ts +++ b/urbanLifelineWeb/packages/platform/src/main.ts @@ -1,3 +1,5 @@ +console.log('📦 main.ts 模块开始加载...') + import { createApp } from 'vue' import { createPinia } from 'pinia' import ElementPlus from 'element-plus' @@ -6,7 +8,6 @@ import 'element-plus/dist/index.css' import App from './App.vue' import router from './router/' import { AES_SECRET_KEY } from './config' -import { initAesEncrypt } from 'shared/utils' // 导入需要的 Lucide 图标(用于动态组件) import { @@ -88,37 +89,41 @@ const lucideIcons = { // 异步初始化应用 async function initApp() { - // 1. 初始化 AES 加密工具 + // 1. 创建 Vue 应用 + const app = createApp(App) + + // 2. 注册 Pinia + const pinia = createPinia() + app.use(pinia) + + // 3. 注册 Element Plus + app.use(ElementPlus) + + // 4. 注册 Lucide 图标(用于动态组件) + for (const [name, component] of Object.entries(lucideIcons)) { + app.component(name, component) + } + + // 5. 注册路由 + app.use(router) + + // 6. 立即挂载应用(不等待 AES 初始化) + app.mount('#app') + + console.log('✅ Platform 应用启动成功') + + // 7. 后台初始化 AES 加密工具(不阻塞渲染) try { + const { initAesEncrypt } = await import('shared/utils') await initAesEncrypt(AES_SECRET_KEY) console.log('✅ AES 加密工具初始化成功') } catch (error) { console.error('❌ AES 加密工具初始化失败:', error) } - - // 2. 创建 Vue 应用 - const app = createApp(App) - - // 3. 注册 Pinia - const pinia = createPinia() - app.use(pinia) - - // 4. 注册 Element Plus - app.use(ElementPlus) - - // 5. 注册 Lucide 图标(用于动态组件) - for (const [name, component] of Object.entries(lucideIcons)) { - app.component(name, component) - } - - // 6. 注册路由 - app.use(router) - - // 7. 挂载应用 - app.mount('#app') - - console.log('✅ Platform 应用启动成功') } // 启动应用 -initApp() +console.log('🚀 开始初始化 Platform 应用...') +initApp().catch(error => { + console.error('❌ 应用初始化失败:', error) +}) diff --git a/urbanLifelineWeb/packages/platform/src/router/dynamicRoute.ts b/urbanLifelineWeb/packages/platform/src/router/dynamicRoute.ts index b5bb96e5..e5396274 100644 --- a/urbanLifelineWeb/packages/platform/src/router/dynamicRoute.ts +++ b/urbanLifelineWeb/packages/platform/src/router/dynamicRoute.ts @@ -9,17 +9,19 @@ /// -import { - generateSimpleRoutes, - loadViewsFromStorage, - type RouteGeneratorConfig, - type GenerateSimpleRoutesOptions -} from 'shared/utils/route' -import type { TbSysViewDTO } from 'shared/types' import type { RouteRecordRaw } from 'vue-router' import router from './index' import { SidebarLayout, BlankLayout, AdminSidebarLayout, SubSidebarLayout } from '@/layouts' +// 动态导入 shared 模块(避免顶层 import 阻塞) +async function loadSharedModules() { + const [routeUtils, types] = await Promise.all([ + import('shared/utils/route'), + import('shared/types') + ]) + return { routeUtils, types } +} + // Platform 布局组件映射 const platformLayoutMap: Record Promise> = { 'SidebarLayout': () => Promise.resolve({ default: SidebarLayout }), @@ -68,7 +70,7 @@ function viewLoader(componentPath: string): (() => Promise) | null { } // Platform 路由生成器配置 -const routeConfig: RouteGeneratorConfig = { +const routeConfig: any = { layoutMap: platformLayoutMap, viewLoader, notFoundComponent: () => Promise.resolve({ @@ -79,7 +81,7 @@ const routeConfig: RouteGeneratorConfig = { } // Platform 路由生成选项 -const routeOptions: GenerateSimpleRoutesOptions = { +const routeOptions: any = { asRootChildren: false, // 直接作为根级路由,不是某个布局的子路由 iframePlaceholder: () => import('shared/components').then(m => ({ default: m.IframeView })), verbose: true // 启用详细日志 @@ -89,7 +91,7 @@ const routeOptions: GenerateSimpleRoutesOptions = { * 添加动态路由(Platform 特定) * @param views 视图列表(用作菜单) */ -export function addDynamicRoutes(views: TbSysViewDTO[]) { +export async function addDynamicRoutes(views: any[]) { if (!views || views.length === 0) { console.warn('[Platform] addDynamicRoutes: 视图列表为空') return @@ -98,6 +100,10 @@ export function addDynamicRoutes(views: TbSysViewDTO[]) { console.log('[Platform] addDynamicRoutes: 开始添加动态路由,视图数量:', views.length) try { + // 动态加载 shared 模块 + const { routeUtils } = await loadSharedModules() + const { generateSimpleRoutes } = routeUtils + // 使用 shared 中的通用方法生成路由 const routes = generateSimpleRoutes(views, routeConfig, routeOptions) @@ -133,10 +139,14 @@ export function addDynamicRoutes(views: TbSysViewDTO[]) { * * 使用 shared 中的通用 loadViewsFromStorage 方法 */ -export function loadRoutesFromStorage(): boolean { +export async function loadRoutesFromStorage(): Promise { try { console.log('[Platform] loadRoutesFromStorage: 开始加载动态路由') + // 动态加载 shared 模块 + const { routeUtils } = await loadSharedModules() + const { loadViewsFromStorage } = routeUtils + // 使用 shared 中的通用方法加载视图数据 const allViews = loadViewsFromStorage('loginDomain', 'userViews') @@ -144,7 +154,7 @@ export function loadRoutesFromStorage(): boolean { if (allViews) { // 过滤出 platform 服务的视图 - const platformViews = allViews.filter((view: TbSysViewDTO) => + const platformViews = allViews.filter((view: any) => view.service === 'platform' ) @@ -156,7 +166,7 @@ export function loadRoutesFromStorage(): boolean { } // 使用 Platform 的 addDynamicRoutes 添加路由 - addDynamicRoutes(platformViews) + await addDynamicRoutes(platformViews) return true } diff --git a/urbanLifelineWeb/packages/platform/src/router/index.ts b/urbanLifelineWeb/packages/platform/src/router/index.ts index af76e120..1d7e882c 100644 --- a/urbanLifelineWeb/packages/platform/src/router/index.ts +++ b/urbanLifelineWeb/packages/platform/src/router/index.ts @@ -1,17 +1,55 @@ import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router' -import { TokenManager } from 'shared/api' +import { h } from 'vue' import { loadRoutesFromStorage } from './dynamicRoute' +// 动态导入 TokenManager(避免顶层 import 阻塞) +let _TokenManager: any = null +async function getTokenManager() { + if (!_TokenManager) { + const module = await import('shared/api') + _TokenManager = module.TokenManager + } + return _TokenManager +} + +// 同步检查 token(用于非异步场景) +function hasTokenSync(): boolean { + try { + const token = localStorage.getItem('token') + return !!token + } catch { + return false + } +} + // platform应用的动态路由会根据layout字段自动添加,不需要预定义Root布局 const routes: RouteRecordRaw[] = [ { - path: '/platform/login', + path: '/login', name: 'Login', component: () => import('@/views/public/Login/Login.vue'), meta: { title: '登录', requiresAuth: false // 不需要登录 } + }, + { + path: '/', + name: 'Root', + component: () => Promise.resolve({ default: { render: () => h('div', '加载中...') } }), + meta: { + title: '首页', + requiresAuth: true // 需要登录 + } + }, + { + path: '/:pathMatch(.*)*', + name: 'NotFound', + component: () => Promise.resolve({ default: { render: () => h('div', { style: { padding: '20px', textAlign: 'center' } }, '404 - 页面未找到') } }), + meta: { + title: '404', + requiresAuth: false // 不需要登录 + } } ] @@ -23,27 +61,27 @@ const router = createRouter({ // 标记动态路由是否已加载 let dynamicRoutesLoaded = false -// 路由守卫 -router.beforeEach((to, from, next) => { +// 路由守卫(使用 async) +router.beforeEach(async (to, from, next) => { // 设置页面标题 if (to.meta.title) { document.title = `${to.meta.title} - 泰豪电源 AI 数智化平台` } - // 检查是否需要登录 + // 检查是否需要登录(使用同步方法,避免阻塞) const requiresAuth = to.meta.requiresAuth !== false // 默认需要登录 - const hasToken = TokenManager.hasToken() + const hasToken = hasTokenSync() if (requiresAuth && !hasToken) { // 需要登录但未登录,跳转到登录页 next({ - path: '/platform/login', + path: '/login', query: { redirect: to.fullPath } // 保存原始路径 }) return } - if (to.path === '/platform/login' && hasToken) { + if (to.path === '/login' && hasToken) { // 已登录但访问登录页,跳转到首页 next('/') return @@ -52,26 +90,28 @@ router.beforeEach((to, from, next) => { // 如果已登录且动态路由未加载,先加载动态路由 if (hasToken && !dynamicRoutesLoaded) { dynamicRoutesLoaded = true - const loaded = loadRoutesFromStorage() - - if (loaded) { - if (to.path === '/') { - // 访问根路径,重定向到第一个可用路由 - const firstRoute = getFirstAvailableRoute() - if (firstRoute && firstRoute !== '/') { - // 只有当第一个路由不是 / 时才重定向,避免无限循环 - console.log('[Platform Router] 根路径重定向到:', firstRoute) - next({ path: firstRoute, replace: true }) - return + try { + const loaded = await loadRoutesFromStorage() + + if (loaded) { + if (to.path === '/') { + // 访问根路径,重定向到第一个可用路由 + const firstRoute = getFirstAvailableRoute() + if (firstRoute && firstRoute !== '/') { + console.log('[Platform Router] 根路径重定向到:', firstRoute) + next({ path: firstRoute, replace: true }) + return + } else { + console.log('[Platform Router] 第一个路由就是根路径,直接放行') + } } else { - // 第一个路由就是 /,直接放行 - console.log('[Platform Router] 第一个路由就是根路径,直接放行') + // 动态路由已加载,重新导航到目标路由 + next({ ...to, replace: true }) + return } - } else { - // 动态路由已加载,重新导航到目标路由 - next({ ...to, replace: true }) - return } + } catch (error) { + console.error('[Platform Router] 加载动态路由失败:', error) } } @@ -79,7 +119,6 @@ router.beforeEach((to, from, next) => { if (hasToken && to.path === '/' && dynamicRoutesLoaded) { const firstRoute = getFirstAvailableRoute() if (firstRoute && firstRoute !== '/') { - // 只有当第一个路由不是 / 时才重定向,避免无限循环 console.log('[Platform Router] 已登录访问根路径,重定向到:', firstRoute) next({ path: firstRoute, replace: true }) return diff --git a/urbanLifelineWeb/packages/platform/vite.config.ts b/urbanLifelineWeb/packages/platform/vite.config.ts index f8a2d7b5..c08a8878 100644 --- a/urbanLifelineWeb/packages/platform/vite.config.ts +++ b/urbanLifelineWeb/packages/platform/vite.config.ts @@ -90,15 +90,30 @@ export default defineConfig(({ mode }) => { build: { target: 'esnext', outDir: 'dist', - sourcemap: true, - rollupOptions: { - output: { - manualChunks: { - 'vue-vendor': ['vue', 'vue-router', 'pinia'], - 'element-plus': ['element-plus'] + sourcemap: true + // 注意:不要使用 manualChunks 分割 vue/vue-router/element-plus + // 因为它们已经在 Module Federation 的 shared 中声明 + // 同时使用会导致循环依赖死锁 + }, + preview: { + port: 7001, + host: true, + cors: true, + https: (() => { + try { + return { + key: fs.readFileSync('C:/Users/FK05/443/localhost+3-key.pem'), + cert: fs.readFileSync('C:/Users/FK05/443/localhost+3.pem') + } + } catch { + return undefined } + })(), + headers: { + 'Access-Control-Allow-Origin': '*', + 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS', + 'Access-Control-Allow-Headers': 'Content-Type, Authorization' } - } } } }) diff --git a/urbanLifelineWeb/packages/shared/vite.config.ts b/urbanLifelineWeb/packages/shared/vite.config.ts index 79d1071f..de6d287f 100644 --- a/urbanLifelineWeb/packages/shared/vite.config.ts +++ b/urbanLifelineWeb/packages/shared/vite.config.ts @@ -135,6 +135,16 @@ export default defineConfig({ port: 7000, host: true, cors: true, + https: (() => { + try { + return { + key: fs.readFileSync('C:/Users/FK05/443/localhost+3-key.pem'), + cert: fs.readFileSync('C:/Users/FK05/443/localhost+3.pem') + } + } catch { + return undefined + } + })(), headers: { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS', diff --git a/urbanLifelineWeb/packages/workcase/.__mf__temp/workcase/localSharedImportMap.js b/urbanLifelineWeb/packages/workcase/.__mf__temp/workcase/localSharedImportMap.js deleted file mode 100644 index 595be568..00000000 --- a/urbanLifelineWeb/packages/workcase/.__mf__temp/workcase/localSharedImportMap.js +++ /dev/null @@ -1,130 +0,0 @@ - -// Windows temporarily needs this file, https://github.com/module-federation/vite/issues/68 - - import {loadShare} from "@module-federation/runtime"; - const importMap = { - - "element-plus": async () => { - let pkg = await import("__mf__virtual/workcase__prebuild__element_mf_2_plus__prebuild__.js"); - return pkg; - } - , - "vue": async () => { - let pkg = await import("__mf__virtual/workcase__prebuild__vue__prebuild__.js"); - return pkg; - } - , - "vue-router": async () => { - let pkg = await import("__mf__virtual/workcase__prebuild__vue_mf_2_router__prebuild__.js"); - return pkg; - } - - } - const usedShared = { - - "element-plus": { - name: "element-plus", - version: "2.12.0", - scope: ["default"], - loaded: false, - from: "workcase", - async get () { - if (false) { - throw new Error(`Shared module '${"element-plus"}' must be provided by host`); - } - usedShared["element-plus"].loaded = true - const {"element-plus": pkgDynamicImport} = importMap - const res = await pkgDynamicImport() - const exportModule = {...res} - // All npm packages pre-built by vite will be converted to esm - Object.defineProperty(exportModule, "__esModule", { - value: true, - enumerable: false - }) - return function () { - return exportModule - } - }, - shareConfig: { - singleton: false, - requiredVersion: "^2.12.0", - - } - } - , - "vue": { - name: "vue", - version: "3.5.25", - scope: ["default"], - loaded: false, - from: "workcase", - async get () { - if (false) { - throw new Error(`Shared module '${"vue"}' must be provided by host`); - } - usedShared["vue"].loaded = true - const {"vue": pkgDynamicImport} = importMap - const res = await pkgDynamicImport() - const exportModule = {...res} - // All npm packages pre-built by vite will be converted to esm - Object.defineProperty(exportModule, "__esModule", { - value: true, - enumerable: false - }) - return function () { - return exportModule - } - }, - shareConfig: { - singleton: false, - requiredVersion: "^3.5.25", - - } - } - , - "vue-router": { - name: "vue-router", - version: "4.6.3", - scope: ["default"], - loaded: false, - from: "workcase", - async get () { - if (false) { - throw new Error(`Shared module '${"vue-router"}' must be provided by host`); - } - usedShared["vue-router"].loaded = true - const {"vue-router": pkgDynamicImport} = importMap - const res = await pkgDynamicImport() - const exportModule = {...res} - // All npm packages pre-built by vite will be converted to esm - Object.defineProperty(exportModule, "__esModule", { - value: true, - enumerable: false - }) - return function () { - return exportModule - } - }, - shareConfig: { - singleton: false, - requiredVersion: "^4.6.3", - - } - } - - } - const usedRemotes = [ - { - entryGlobalName: "shared", - name: "shared", - type: "module", - entry: "/shared/mf-manifest.json", - shareScope: "default", - } - - ] - export { - usedShared, - usedRemotes - } - \ No newline at end of file diff --git a/urbanLifelineWeb/packages/workcase/index.html b/urbanLifelineWeb/packages/workcase/index.html index 7b994e53..73dc6202 100644 --- a/urbanLifelineWeb/packages/workcase/index.html +++ b/urbanLifelineWeb/packages/workcase/index.html @@ -7,7 +7,7 @@ 案例管理系统 - +
diff --git a/urbanLifelineWeb/packages/workcase/public/app-config.local.js b/urbanLifelineWeb/packages/workcase/public/app-config.local.js new file mode 100644 index 00000000..b870e164 --- /dev/null +++ b/urbanLifelineWeb/packages/workcase/public/app-config.local.js @@ -0,0 +1,65 @@ +/** + * @description 本地开发环境配置文件 + * 用于 dev 和 preview 模式 + */ + +window.APP_RUNTIME_CONFIG = { + // 环境标识 + env: 'production', + + // API 配置 + api: { + baseUrl: 'https://org.xyzh.yslg/api', + timeout: 30000 + }, + + // 应用基础路径 + baseUrl: '/workcase/', + + // 文件配置 + file: { + downloadUrl: 'https://org.xyzh.yslg/api/urban-lifeline/file/download/', + uploadUrl: 'https://org.xyzh.yslg/api/urban-lifeline/file/upload', + maxSize: { + image: 5, + video: 100, + document: 10 + }, + acceptTypes: { + image: 'image/*', + video: 'video/*', + document: '.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx' + } + }, + + // Token 配置 + token: { + key: 'token', + refreshThreshold: 300000 + }, + + // 公共资源路径 + publicImgPath: '/workcase/img', + publicWebPath: '/workcase', + + // 单点登录配置 + sso: { + platformUrl: 'https://org.xyzh.yslg/platform/', + workcaseUrl: 'https://org.xyzh.yslg/workcase/', + biddingUrl: 'https://org.xyzh.yslg/bidding/' + }, + + // AES 加密密钥(本地开发用,生产环境需要替换) + aesSecretKey: 'MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=', + + // Jitsi 视频会议配置 + jitsi: { + serverUrl: 'https://meet.jit.si' + }, + + // 功能开关 + features: { + enableDebug: true, + enableMockData: false + } +}; diff --git a/urbanLifelineWeb/packages/workcase/src/main.ts b/urbanLifelineWeb/packages/workcase/src/main.ts index 01eab3e0..ef72afb8 100644 --- a/urbanLifelineWeb/packages/workcase/src/main.ts +++ b/urbanLifelineWeb/packages/workcase/src/main.ts @@ -8,8 +8,6 @@ import './assets/css/common.scss' import App from './App.vue' import router from './router/' import { AES_SECRET_KEY } from './config/index' -// @ts-ignore -import { initAesEncrypt } from 'shared/utils' // 导入需要的 Lucide 图标(用于动态组件) import { @@ -89,37 +87,41 @@ const lucideIcons = { // 异步初始化应用 async function initApp() { - // 1. 初始化 AES 加密工具 + // 1. 创建 Vue 应用 + const app = createApp(App) + + // 2. 注册 Pinia + const pinia = createPinia() + app.use(pinia) + + // 3. 注册 Element Plus + app.use(ElementPlus) + + // 4. 注册 Lucide 图标(用于动态组件) + for (const [name, component] of Object.entries(lucideIcons)) { + app.component(name, component) + } + + // 5. 注册路由 + app.use(router) + + // 6. 立即挂载应用(不等待 AES 初始化) + app.mount('#app') + + console.log('✅ Workcase 应用启动成功') + + // 7. 后台初始化 AES 加密工具(不阻塞渲染) try { + const { initAesEncrypt } = await import('shared/utils') await initAesEncrypt(AES_SECRET_KEY) console.log('✅ AES 加密工具初始化成功') } catch (error) { console.error('❌ AES 加密工具初始化失败:', error) } - - // 2. 创建 Vue 应用 - const app = createApp(App) - - // 3. 注册 Pinia - const pinia = createPinia() - app.use(pinia) - - // 4. 注册 Element Plus - app.use(ElementPlus) - - // 5. 注册 Lucide 图标(用于动态组件) - for (const [name, component] of Object.entries(lucideIcons)) { - app.component(name, component) - } - - // 6. 注册路由 - app.use(router) - - // 7. 挂载应用 - app.mount('#app') - - console.log('✅ Workcase 应用启动成功') } // 启动应用 -initApp() +console.log('🚀 开始初始化 Workcase 应用...') +initApp().catch(error => { + console.error('❌ 应用初始化失败:', error) +}) diff --git a/urbanLifelineWeb/packages/workcase/src/router/dynamicRoute.ts b/urbanLifelineWeb/packages/workcase/src/router/dynamicRoute.ts index 46103145..345e2de6 100644 --- a/urbanLifelineWeb/packages/workcase/src/router/dynamicRoute.ts +++ b/urbanLifelineWeb/packages/workcase/src/router/dynamicRoute.ts @@ -9,17 +9,19 @@ /// -import { - generateSimpleRoutes, - loadViewsFromStorage, - type RouteGeneratorConfig, - type GenerateSimpleRoutesOptions -} from 'shared/utils/route' -import type { TbSysViewDTO } from 'shared/types' import type { RouteRecordRaw } from 'vue-router' import router from './index' import { SidebarLayout, BlankLayout, SubSidebarLayout } from '@/layouts' +// 动态导入 shared 模块(避免顶层 import 阻塞) +async function loadSharedModules() { + const [routeUtils, types] = await Promise.all([ + import('shared/utils/route'), + import('shared/types') + ]) + return { routeUtils, types } +} + // Workcase 布局组件映射 const workcaseLayoutMap: Record Promise> = { 'SidebarLayout': () => Promise.resolve({ default: SidebarLayout }), @@ -67,7 +69,7 @@ function viewLoader(componentPath: string): (() => Promise) | null { } // Workcase 路由生成器配置 -const routeConfig: RouteGeneratorConfig = { +const routeConfig: any = { layoutMap: workcaseLayoutMap, viewLoader, notFoundComponent: () => Promise.resolve({ @@ -78,7 +80,7 @@ const routeConfig: RouteGeneratorConfig = { } // Workcase 路由生成选项 -const routeOptions: GenerateSimpleRoutesOptions = { +const routeOptions: any = { asRootChildren: false, // 直接作为根级路由,不是某个布局的子路由 iframePlaceholder: () => import('shared/components').then(m => ({ default: m.IframeView })), verbose: true // 启用详细日志 @@ -88,17 +90,19 @@ const routeOptions: GenerateSimpleRoutesOptions = { * 添加动态路由(Workcase 特定) * @param views 视图列表(用作菜单) */ -export function addDynamicRoutes(views: TbSysViewDTO[]) { +export async function addDynamicRoutes(views: any[]) { if (!views || views.length === 0) { console.warn('[Workcase] addDynamicRoutes: 视图列表为空') return } console.log('[Workcase] addDynamicRoutes: 开始添加动态路由,视图数量:', views.length) - console.log('[Workcase] addDynamicRoutes: 路由配置:', routeConfig) - console.log('[Workcase] addDynamicRoutes: 路由选项:', routeOptions) try { + // 动态加载 shared 模块 + const { routeUtils } = await loadSharedModules() + const { generateSimpleRoutes } = routeUtils + // 使用 shared 中的通用方法生成路由 const routes = generateSimpleRoutes(views, routeConfig, routeOptions) @@ -109,6 +113,7 @@ export function addDynamicRoutes(views: TbSysViewDTO[]) { }) } catch (error) { + console.error('[Workcase] addDynamicRoutes: 添加路由失败', error) throw error } } @@ -119,10 +124,14 @@ export function addDynamicRoutes(views: TbSysViewDTO[]) { * 使用 shared 中的通用 loadViewsFromStorage 方法 * 筛选出 service='workcase' 的视图 */ -export function loadRoutesFromStorage(): boolean { +export async function loadRoutesFromStorage(): Promise { try { console.log('[Workcase] loadRoutesFromStorage: 开始加载动态路由') + // 动态加载 shared 模块 + const { routeUtils } = await loadSharedModules() + const { loadViewsFromStorage } = routeUtils + // 使用 shared 中的通用方法加载视图数据 const allViews = loadViewsFromStorage('loginDomain', 'userViews') @@ -130,7 +139,7 @@ export function loadRoutesFromStorage(): boolean { if (allViews) { // 过滤出 workcase 服务的视图 - const workcaseViews = allViews.filter((view: TbSysViewDTO) => + const workcaseViews = allViews.filter((view: any) => view.service === 'workcase' ) @@ -142,7 +151,7 @@ export function loadRoutesFromStorage(): boolean { } // 使用 Workcase 的 addDynamicRoutes 添加路由 - addDynamicRoutes(workcaseViews) + await addDynamicRoutes(workcaseViews) return true } diff --git a/urbanLifelineWeb/packages/workcase/src/router/index.ts b/urbanLifelineWeb/packages/workcase/src/router/index.ts index a68dc7c8..b5079c55 100644 --- a/urbanLifelineWeb/packages/workcase/src/router/index.ts +++ b/urbanLifelineWeb/packages/workcase/src/router/index.ts @@ -1,11 +1,22 @@ import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router' -// @ts-ignore -import { TokenManager } from 'shared/api' -// @ts-ignore -import { APP_CONFIG } from 'shared/config' -// @ts-ignore import { loadRoutesFromStorage } from './dynamicRoute' +// 同步检查 token(用于非异步场景) +function hasTokenSync(): boolean { + try { + const token = localStorage.getItem('token') + return !!token + } catch { + return false + } +} + +// 动态获取 TokenManager +async function getTokenManager() { + const module = await import('shared/api') + return module.TokenManager +} + // 公开路由(不需要登录认证) const routes: RouteRecordRaw[] = [ { @@ -64,7 +75,8 @@ router.beforeEach(async (to, from, next) => { const newToken = loginDomain.token // 保存到localStorage(覆盖旧的登录状态) - // 只用 TokenManager 存储 token,避免格式不一致 + // 动态获取 TokenManager + const TokenManager = await getTokenManager() TokenManager.setToken(newToken) localStorage.setItem('loginDomain', JSON.stringify(loginDomain)) @@ -80,9 +92,9 @@ router.beforeEach(async (to, from, next) => { } } - // 检查是否需要登录 + // 检查是否需要登录(使用同步方法) const requiresAuth = to.meta.requiresAuth !== false - const hasToken = TokenManager.hasToken() + const hasToken = hasTokenSync() console.log('[Workcase Router] 认证检查:', { requiresAuth, @@ -116,41 +128,45 @@ router.beforeEach(async (to, from, next) => { }) dynamicRoutesLoaded = true - const loaded = loadRoutesFromStorage?.() + try { + const loaded = await loadRoutesFromStorage() - console.log('[Workcase Router] 动态路由加载结果:', loaded) - console.log('[Workcase Router] 当前路径:', to.path) - console.log('[Workcase Router] 所有路由:', router.getRoutes().map(r => r.path)) + console.log('[Workcase Router] 动态路由加载结果:', loaded) + console.log('[Workcase Router] 当前路径:', to.path) + console.log('[Workcase Router] 所有路由:', router.getRoutes().map(r => r.path)) - if (loaded) { - if (to.path === '/') { - // 访问根路径,重定向到第一个可用路由 - const firstRoute = getFirstAvailableRoute() - if (firstRoute && firstRoute !== '/') { - // 只有当第一个路由不是 / 时才重定向,避免无限循环 - console.log('[Workcase Router] 根路径重定向到:', firstRoute) - next({ path: firstRoute, replace: true }) - return + if (loaded) { + if (to.path === '/') { + // 访问根路径,重定向到第一个可用路由 + const firstRoute = getFirstAvailableRoute() + if (firstRoute && firstRoute !== '/') { + // 只有当第一个路由不是 / 时才重定向,避免无限循环 + console.log('[Workcase Router] 根路径重定向到:', firstRoute) + next({ path: firstRoute, replace: true }) + return + } else { + // 第一个路由就是 /,直接放行 + console.log('[Workcase Router] 第一个路由就是根路径,直接放行') + } + } else if (to.path === '/admin') { + // 访问 /admin 路径,重定向到第一个 admin 路由 + const firstAdminRoute = getFirstAdminRoute() + if (firstAdminRoute) { + console.log('[Workcase Router] /admin 重定向到:', firstAdminRoute) + next({ path: firstAdminRoute, replace: true }) + return + } } else { - // 第一个路由就是 /,直接放行 - console.log('[Workcase Router] 第一个路由就是根路径,直接放行') - } - } else if (to.path === '/admin') { - // 访问 /admin 路径,重定向到第一个 admin 路由 - const firstAdminRoute = getFirstAdminRoute() - if (firstAdminRoute) { - console.log('[Workcase Router] /admin 重定向到:', firstAdminRoute) - next({ path: firstAdminRoute, replace: true }) + // 动态路由加载成功,重新导航以匹配新添加的路由 + console.log('[Workcase Router] 动态路由加载成功,重新导航到:', to.path) + next({ ...to, replace: true }) return } } else { - // 动态路由加载成功,重新导航以匹配新添加的路由 - console.log('[Workcase Router] 动态路由加载成功,重新导航到:', to.path) - next({ ...to, replace: true }) - return + console.warn('[Workcase Router] 动态路由加载失败') } - } else { - console.warn('[Workcase Router] 动态路由加载失败') + } catch (error) { + console.error('[Workcase Router] 加载动态路由失败:', error) } } diff --git a/urbanLifelineWeb/packages/workcase/vite.config.ts b/urbanLifelineWeb/packages/workcase/vite.config.ts index 8e818588..00e663b4 100644 --- a/urbanLifelineWeb/packages/workcase/vite.config.ts +++ b/urbanLifelineWeb/packages/workcase/vite.config.ts @@ -14,8 +14,11 @@ const DEV_SHARED_URL = 'https://localhost:7000/shared/remoteEntry.js' // 生产环境使用相对路径,通过 Nginx 代理访问 const PROD_SHARED_URL = '/shared/remoteEntry.js' -export default defineConfig(({ mode }) => { +export default defineConfig(({ mode, command }) => { + // dev 和 preview 都需要访问本地 shared 服务 + // command: 'serve' (dev), 'build', 或通过环境变量判断 preview const isDev = mode === 'development' + // preview 模式通过 nginx 代理访问 shared,使用相对路径 const sharedEntry = isDev ? DEV_SHARED_URL : PROD_SHARED_URL return { @@ -88,19 +91,33 @@ export default defineConfig(({ mode }) => { } } }, - + preview: { + port: 7003, + host: true, + cors: true, + https: (() => { + try { + return { + key: fs.readFileSync('C:/Users/FK05/443/localhost+3-key.pem'), + cert: fs.readFileSync('C:/Users/FK05/443/localhost+3.pem') + } + } catch { + return undefined + } + })(), + headers: { + 'Access-Control-Allow-Origin': '*', + 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS', + 'Access-Control-Allow-Headers': 'Content-Type, Authorization' + } + }, build: { target: 'esnext', outDir: 'dist', - sourcemap: true, - rollupOptions: { - output: { - manualChunks: { - 'vue-vendor': ['vue', 'vue-router', 'pinia'], - 'element-plus': ['element-plus'] - } - } - } + sourcemap: true + // 注意:不要使用 manualChunks 分割 vue/vue-router/element-plus + // 因为它们已经在 Module Federation 的 shared 中声明 + // 同时使用会导致循环依赖死锁 } } })