Module Federation 在大型企业级应用中的架构设计需要考虑多个方面,以下是详细的架构方案:
1. 多层级架构设计
三层架构模式:
shell┌─────────────────────────────────────────┐ │ 主应用层 (Host Layer) │ │ - 路由管理 │ │ - 全局状态管理 │ │ - 用户认证授权 │ └──────────────┬──────────────────────────┘ │ ┌──────────────▼──────────────────────────┐ │ 业务模块层 (Business Layer) │ │ - 订单模块 (Order Module) │ │ - 用户模块 (User Module) │ │ - 支付模块 (Payment Module) │ └──────────────┬──────────────────────────┘ │ ┌──────────────▼──────────────────────────┐ │ 基础组件层 (Component Layer) │ │ - UI 组件库 │ │ - 工具函数库 │ │ - 业务组件 │ └─────────────────────────────────────────┘
2. 模块划分策略
按业务域划分:
javascript// 订单模块 new ModuleFederationPlugin({ name: 'orderModule', filename: 'remoteEntry.js', exposes: { './OrderList': './src/OrderList', './OrderDetail': './src/OrderDetail', './OrderCreate': './src/OrderCreate', './OrderAPI': './src/api/order' }, shared: { react: { singleton: true }, 'react-dom': { singleton: true }, '@company/ui-components': { singleton: true }, '@company/utils': { singleton: true } } }) // 用户模块 new ModuleFederationPlugin({ name: 'userModule', filename: 'remoteEntry.js', exposes: { './UserProfile': './src/UserProfile', './UserSettings': './src/UserSettings', './UserAPI': './src/api/user' }, shared: { react: { singleton: true }, 'react-dom': { singleton: true }, '@company/ui-components': { singleton: true } } })
按功能层次划分:
javascript// 基础组件库 new ModuleFederationPlugin({ name: 'componentLibrary', filename: 'remoteEntry.js', exposes: { './Button': './src/components/Button', './Modal': './src/components/Modal', './Table': './src/components/Table', './Form': './src/components/Form' }, shared: { react: { singleton: true }, 'react-dom': { singleton: true }, 'styled-components': { singleton: true } } }) // 工具库 new ModuleFederationPlugin({ name: 'utilityLibrary', filename: 'remoteEntry.js', exposes: { './request': './src/utils/request', './storage': './src/utils/storage', './validation': './src/utils/validation', './format': './src/utils/format' }, shared: {} })
3. 状态管理架构
集中式状态管理:
javascript// 主应用状态管理 import { createStore } from 'redux' import { Provider } from 'react-redux' const rootReducer = combineReducers({ auth: authReducer, theme: themeReducer, // 远程模块的 reducer 会在运行时注册 modules: (state = {}, action) => { // 动态注册的模块 reducer return moduleReducers.reduce((acc, reducer) => { return reducer(acc, action) }, state) } }) const store = createStore(rootReducer) // 远程模块注册 reducer export const registerModuleReducer = (name, reducer) => { moduleReducers.push(reducer) store.replaceReducer(createRootReducer()) }
分布式状态管理:
javascript// 使用事件总线实现跨模块通信 class EventBus { constructor() { this.events = {} } on(event, callback) { if (!this.events[event]) { this.events[event] = [] } this.events[event].push(callback) } emit(event, data) { if (this.events[event]) { this.events[event].forEach(callback => callback(data)) } } off(event, callback) { if (this.events[event]) { this.events[event] = this.events[event].filter(cb => cb !== callback) } } } export const eventBus = new EventBus() // 远程模块使用事件总线 import { eventBus } from '@company/event-bus' // 发布事件 eventBus.emit('order:created', { orderId: 123 }) // 订阅事件 eventBus.on('order:created', (data) => { console.log('Order created:', data) })
4. 路由架构设计
主应用路由配置:
javascriptimport { BrowserRouter, Routes, Route } from 'react-router-dom' const routes = [ { path: '/orders', component: React.lazy(() => import('orderModule/OrderList')) }, { path: '/orders/:id', component: React.lazy(() => import('orderModule/OrderDetail')) }, { path: '/users', component: React.lazy(() => import('userModule/UserProfile')) }, { path: '/settings', component: React.lazy(() => import('userModule/UserSettings')) } ] function App() { return ( <BrowserRouter> <Suspense fallback={<Loading />}> <Routes> {routes.map((route, index) => ( <Route key={index} path={route.path} element={<route.component />} /> ))} </Routes> </Suspense> </BrowserRouter> ) }
动态路由加载:
javascript// 路由配置文件 const routeConfig = { '/orders': { module: 'orderModule', component: 'OrderList', permissions: ['orders:read'] }, '/orders/create': { module: 'orderModule', component: 'OrderCreate', permissions: ['orders:create'] } } // 动态路由加载器 const loadRoute = async (path) => { const config = routeConfig[path] if (!config) return null const { module, component } = config const Component = await import(`${module}/${component}`) return Component.default }
5. 依赖管理策略
统一依赖版本:
json// 根目录 package.json { "name": "monorepo", "private": true, "workspaces": [ "packages/*" ], "scripts": { "sync-deps": "sync-dependencies" }, "devDependencies": { "sync-dependencies": "^1.0.0" } }
依赖同步脚本:
javascript// scripts/sync-dependencies.js const fs = require('fs') const path = require('path') const sharedDependencies = { react: '^17.0.2', 'react-dom': '^17.0.2', 'react-router-dom': '^6.0.0', 'styled-components': '^5.3.0' } const packagesDir = path.join(__dirname, '../packages') fs.readdirSync(packagesDir).forEach(pkgName => { const pkgPath = path.join(packagesDir, pkgName, 'package.json') if (fs.existsSync(pkgPath)) { const pkg = require(pkgPath) pkg.dependencies = { ...pkg.dependencies, ...sharedDependencies } fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2)) } })
6. 性能优化架构
预加载策略:
javascript// 智能预加载器 class PreloadManager { constructor() { this.preloadedModules = new Set() this.preloadQueue = [] } preload(moduleName) { if (this.preloadedModules.has(moduleName)) return this.preloadQueue.push(moduleName) this.processQueue() } async processQueue() { if (this.isProcessing) return this.isProcessing = true while (this.preloadQueue.length > 0) { const moduleName = this.preloadQueue.shift() try { await import(moduleName) this.preloadedModules.add(moduleName) } catch (error) { console.error(`Failed to preload ${moduleName}:`, error) } } this.isProcessing = false } } export const preloadManager = new PreloadManager() // 使用示例 preloadManager.preload('orderModule/OrderList')
缓存策略:
javascript// Service Worker 缓存配置 const CACHE_NAME = 'module-federation-v1' const CACHE_URLS = [ '/remoteEntry.js', '/main.js', '/vendor.js' ] self.addEventListener('install', (event) => { event.waitUntil( caches.open(CACHE_NAME).then((cache) => { return cache.addAll(CACHE_URLS) }) ) }) self.addEventListener('fetch', (event) => { event.respondWith( caches.match(event.request).then((response) => { return response || fetch(event.request) }) ) })
7. 监控和日志架构
模块加载监控:
javascript// 模块加载追踪器 class ModuleTracker { constructor() { this.loadTimes = new Map() this.errorCounts = new Map() } track(moduleName, status, duration) { const key = `${moduleName}_${status}` const count = this.errorCounts.get(key) || 0 this.errorCounts.set(key, count + 1) if (status === 'success') { this.loadTimes.set(moduleName, duration) } // 发送到监控系统 this.sendToMonitoring({ module: moduleName, status, duration, timestamp: Date.now() }) } sendToMonitoring(data) { // 发送到后端监控系统 fetch('/api/monitoring/modules', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }).catch(console.error) } } export const moduleTracker = new ModuleTracker()
8. 灾难恢复架构
降级策略:
javascript// 模块降级管理器 class FallbackManager { constructor() { this.fallbacks = new Map() } register(moduleName, fallbackComponent) { this.fallbacks.set(moduleName, fallbackComponent) } async loadWithFallback(moduleName) { try { const module = await import(moduleName) return module.default } catch (error) { console.error(`Failed to load ${moduleName}, using fallback`) const fallback = this.fallbacks.get(moduleName) if (fallback) { return fallback } throw error } } } export const fallbackManager = new FallbackManager() // 注册降级组件 fallbackManager.register('orderModule/OrderList', LocalOrderList)
通过以上架构设计,可以构建一个可扩展、高性能、易维护的企业级 Module Federation 应用。