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

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

View File

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