web打包问题

This commit is contained in:
2026-01-07 15:30:29 +08:00
parent ec61f134a8
commit 72cea2935d
22 changed files with 762 additions and 335 deletions

View File

@@ -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 模式下出现空白页面的问题,确保应用能够正常初始化和运行。

View File

@@ -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
}
}
]
}

View File

@@ -7,7 +7,7 @@
<title>招标管理系统</title>
<!-- 加载运行时配置(必须在其他脚本之前加载) -->
<script src="/app-config.js"></script>
<script src="/app-config.local.js"></script>
<!-- Import Maps 配置 - 引用共享模块 -->
<script type="importmap">

View File

@@ -0,0 +1,60 @@
/**
* @description 本地开发环境配置文件
* 用于 dev 和 preview 模式
*/
window.APP_RUNTIME_CONFIG = {
// 环境标识
env: 'production',
// API 配置
api: {
baseUrl: 'https://org.xyzh.yslg/api',
timeout: 30000
},
// 应用基础路径
baseUrl: '/bidding/',
// 文件配置
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: '/bidding/img',
publicWebPath: '/bidding',
// 单点登录配置
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
}
};

View File

@@ -5,7 +5,6 @@ import 'element-plus/dist/index.css'
import App from './App.vue'
import router from './router/'
import { AES_SECRET_KEY } from './config'
// 导入需要的 Lucide 图标
import {

View File

@@ -9,17 +9,19 @@
/// <reference types="vite/client" />
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 }
}
// Bidding 布局组件映射
const biddingLayoutMap: Record<string, () => Promise<any>> = {
'SidebarLayout': () => Promise.resolve({ default: SidebarLayout }),
@@ -67,7 +69,7 @@ function viewLoader(componentPath: string): (() => Promise<any>) | null {
}
// Bidding 路由生成器配置
const routeConfig: RouteGeneratorConfig = {
const routeConfig: any = {
layoutMap: biddingLayoutMap,
viewLoader,
notFoundComponent: () => import('vue').then(({ h }) => ({
@@ -78,7 +80,7 @@ const routeConfig: RouteGeneratorConfig = {
}
// Bidding 路由生成选项
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 = {
* 添加动态路由Bidding 特定)
* @param views 视图列表(用作菜单)
*/
export function addDynamicRoutes(views: TbSysViewDTO[]) {
export async function addDynamicRoutes(views: any[]) {
if (!views || views.length === 0) {
console.warn('[Bidding] addDynamicRoutes: 视图列表为空')
return
}
console.log('[Bidding] addDynamicRoutes: 开始添加动态路由,视图数量:', views.length)
console.log('[Bidding] addDynamicRoutes: 路由配置:', routeConfig)
console.log('[Bidding] addDynamicRoutes: 路由选项:', routeOptions)
try {
// 动态加载 shared 模块
const { routeUtils } = await loadSharedModules()
const { generateSimpleRoutes } = routeUtils
// 使用 shared 中的通用方法生成路由
const routes = generateSimpleRoutes(views, routeConfig, routeOptions)
@@ -120,10 +124,14 @@ export function addDynamicRoutes(views: TbSysViewDTO[]) {
* 使用 shared 中的通用 loadViewsFromStorage 方法
* 筛选出 service='bidding' 的视图
*/
export function loadRoutesFromStorage(): boolean {
export async function loadRoutesFromStorage(): Promise<boolean> {
try {
console.log('[Bidding] loadRoutesFromStorage: 开始加载动态路由')
// 动态加载 shared 模块
const { routeUtils } = await loadSharedModules()
const { loadViewsFromStorage } = routeUtils
// 使用 shared 中的通用方法加载视图数据
const allViews = loadViewsFromStorage('loginDomain', 'userViews')
@@ -131,7 +139,7 @@ export function loadRoutesFromStorage(): boolean {
if (allViews) {
// 过滤出 bidding 服务的视图
const biddingViews = allViews.filter((view: TbSysViewDTO) =>
const biddingViews = allViews.filter((view: any) =>
view.service === 'bidding'
)
@@ -143,7 +151,7 @@ export function loadRoutesFromStorage(): boolean {
}
// 使用 Bidding 的 addDynamicRoutes 添加路由
addDynamicRoutes(biddingViews)
await addDynamicRoutes(biddingViews)
return true
}

View File

@@ -1,11 +1,13 @@
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
// @ts-ignore
import { TokenManager } from 'shared/api'
// @ts-ignore
import { APP_CONFIG } from 'shared/config'
// @ts-ignore
// @ts-ignore - 动态导入,避免顶层 import 阻塞
import { loadRoutesFromStorage } from './dynamicRoute'
// 同步检查 token直接读取 localStorage避免导入 shared 模块)
function hasTokenSync(): boolean {
const token = localStorage.getItem('token')
return !!token && token.length > 0
}
// bidding应用的动态路由会根据layout字段自动添加不需要预定义Root布局
const routes: RouteRecordRaw[] = []
@@ -18,7 +20,7 @@ const router = createRouter({
let dynamicRoutesLoaded = false
// 路由守卫
router.beforeEach((to, from, next) => {
router.beforeEach(async (to, from, next) => {
console.log('[Bidding Router] 路由守卫触发:', {
to: to.path,
from: from.path,
@@ -32,7 +34,7 @@ router.beforeEach((to, from, next) => {
// 检查是否需要登录
const requiresAuth = to.meta.requiresAuth !== false
const hasToken = TokenManager.hasToken()
const hasToken = hasTokenSync()
console.log('[Bidding Router] 认证检查:', {
requiresAuth,
@@ -66,7 +68,9 @@ router.beforeEach((to, from, next) => {
})
dynamicRoutesLoaded = true
const loaded = loadRoutesFromStorage?.()
try {
const loaded = await loadRoutesFromStorage?.()
console.log('[Bidding Router] 动态路由加载结果:', loaded)
console.log('[Bidding Router] 当前路径:', to.path)
@@ -80,6 +84,9 @@ router.beforeEach((to, from, next) => {
} else {
console.warn('[Bidding Router] 动态路由加载失败')
}
} catch (error) {
console.error('[Bidding Router] 动态路由加载异常:', error)
}
}
console.log('[Bidding Router] 继续正常导航')

View File

@@ -90,14 +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: 7002,
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'
}
}
}

View File

@@ -7,7 +7,7 @@
<title>泰豪电源 AI 数智化平台</title>
<!-- 加载运行时配置(必须在其他脚本之前加载) -->
<script src="/app-config.js"></script>
<script src="/app-config.local.js"></script>
</head>
<body>
<div id="app"></div>

View File

@@ -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
}
};

View File

@@ -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)
})

View File

@@ -9,17 +9,19 @@
/// <reference types="vite/client" />
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<string, () => Promise<any>> = {
'SidebarLayout': () => Promise.resolve({ default: SidebarLayout }),
@@ -68,7 +70,7 @@ function viewLoader(componentPath: string): (() => Promise<any>) | 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<boolean> {
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
}

View File

@@ -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,19 +90,18 @@ router.beforeEach((to, from, next) => {
// 如果已登录且动态路由未加载,先加载动态路由
if (hasToken && !dynamicRoutesLoaded) {
dynamicRoutesLoaded = true
const loaded = loadRoutesFromStorage()
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 {
@@ -73,13 +110,15 @@ router.beforeEach((to, from, next) => {
return
}
}
} catch (error) {
console.error('[Platform Router] 加载动态路由失败:', error)
}
}
// 如果已登录且访问根路径,但动态路由已加载,重定向到第一个可用路由
if (hasToken && to.path === '/' && dynamicRoutesLoaded) {
const firstRoute = getFirstAvailableRoute()
if (firstRoute && firstRoute !== '/') {
// 只有当第一个路由不是 / 时才重定向,避免无限循环
console.log('[Platform Router] 已登录访问根路径,重定向到:', firstRoute)
next({ path: firstRoute, replace: true })
return

View File

@@ -90,14 +90,29 @@ 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'
}
}
}

View File

@@ -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',

View File

@@ -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
}

View File

@@ -7,7 +7,7 @@
<title>案例管理系统</title>
<!-- 加载运行时配置(必须在其他脚本之前加载) -->
<script src="/app-config.js"></script>
<script src="/app-config.local.js"></script>
</head>
<body>
<div id="app"></div>

View File

@@ -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
}
};

View File

@@ -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)
})

View File

@@ -9,17 +9,19 @@
/// <reference types="vite/client" />
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<string, () => Promise<any>> = {
'SidebarLayout': () => Promise.resolve({ default: SidebarLayout }),
@@ -67,7 +69,7 @@ function viewLoader(componentPath: string): (() => Promise<any>) | 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<boolean> {
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
}

View File

@@ -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,7 +128,8 @@ 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)
@@ -152,6 +165,9 @@ router.beforeEach(async (to, from, next) => {
} else {
console.warn('[Workcase Router] 动态路由加载失败')
}
} catch (error) {
console.error('[Workcase Router] 加载动态路由失败:', error)
}
}
// 如果已登录且访问根路径,但动态路由已加载,重定向到第一个可用路由

View File

@@ -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 中声明
// 同时使用会导致循环依赖死锁
}
}
})