Module Federation 的性能优化可以从多个维度进行,以下是详细的优化策略:
1. 构建产物优化
代码分割:
javascript// Remote 应用配置 new ModuleFederationPlugin({ name: 'remoteApp', filename: 'remoteEntry.js', exposes: { './Button': './src/Button', './Modal': './src/Modal' }, // 细粒度暴露,避免打包不必要的内容 splitChunks: { chunks: 'all', cacheGroups: { vendor: { test: /[\\/]node_modules[\\/]/, name: 'vendors', priority: 10 } } } })
Tree Shaking:
- 确保使用 ES Module 语法
- 在 package.json 中设置
"sideEffects": false - 避免使用 CommonJS 的 require
2. 加载性能优化
预加载关键模块:
javascript// 在应用空闲时预加载 const preloadRemoteModule = () => { if ('requestIdleCallback' in window) { requestIdleCallback(() => { import('remoteApp/HeavyComponent') }) } } // 或使用 link 标签预加载 const link = document.createElement('link') link.rel = 'preload' link.href = 'http://localhost:3001/remoteEntry.js' link.as = 'script' document.head.appendChild(link)
CDN 部署:
- 将 remoteEntry.js 和模块文件部署到 CDN
- 使用 HTTP/2 或 HTTP/3 加速传输
- 配置合理的缓存策略(Cache-Control: max-age=31536000)
3. 运行时优化
共享依赖优化:
javascriptshared: { react: { singleton: true, requiredVersion: deps.react, eager: false, // 避免急切加载 strictVersion: false // 允许版本不匹配 } }
懒加载策略:
javascript// 使用 React.lazy 和 Suspense const RemoteComponent = React.lazy(() => import('remoteApp/Component') ) // 或使用动态导入 const loadModule = async () => { const module = await import('remoteApp/Module') return module.default }
4. 缓存策略
版本化文件名:
javascript// Webpack 配置 output: { filename: '[name].[contenthash].js', chunkFilename: '[name].[contenthash].js' }
Service Worker 缓存:
javascript// 缓存 remoteEntry.js workbox.routing.registerRoute( /.*remoteEntry\.js/, new workbox.strategies.NetworkFirst({ cacheName: 'remote-entries', plugins: [ new workbox.expiration.ExpirationPlugin({ maxEntries: 10, maxAgeSeconds: 7 * 24 * 60 * 60 }) ] }) )
5. 监控和诊断
性能监控:
javascript// 监控模块加载时间 const loadRemoteModule = async (moduleName) => { const startTime = performance.now() try { const module = await import(moduleName) const loadTime = performance.now() - startTime console.log(`${moduleName} loaded in ${loadTime}ms`) return module } catch (error) { console.error(`Failed to load ${moduleName}:`, error) throw error } }
6. 最佳实践
- 按需暴露:只暴露必要的模块,避免打包不相关的代码
- 版本控制:使用语义化版本管理,确保兼容性
- 错误边界:为远程模块添加错误边界,避免影响整个应用
- 降级方案:准备本地降级组件,应对远程加载失败
- 渐进式加载:优先加载核心功能,次要功能延迟加载
性能指标:
- 首次内容绘制(FCP)< 1.8s
- 最大内容绘制(LCP)< 2.5s
- 累积布局偏移(CLS)< 0.1
- 首次输入延迟(FID)< 100ms
通过以上优化策略,可以显著提升 Module Federation 应用的性能表现。