文章目录
- 微前端(Micro-Frontend): 多个前端团队独立开发/部署 技术栈无关(React/Vue/Angular混合) 增量升级(逐步迁移) vs 单体前端: 单体:所有功能打包到一个bundle(大) 微前端:按功能拆分(小,按需加载) 2026年趋势: Module Federation 2.0(Webpack 5+) RSC(React Server Components) Edge-side Includes(边缘包含)
- 1. 重复依赖(多个子应用都包含React) 网络瀑布流(串行加载多个子应用) 初始化阻塞(主应用等待子应用) 缓存失效(版本更新导致缓存失效)
-
- // webpack.config.js(远程应用/子应用) const { ModuleFederationPlugin } = require('webpack').container; module.exports = { plugins: [ new ModuleFederationPlugin({ name: 'remote_app', filename: 'remoteEntry.js', // 远程入口文件 exposes: { './Button': './src/Button', // 暴露模块 './Modal': './src/Modal', }, shared: { // 共享依赖(避免重复加载) react: { singleton: true, requiredVersion: '^18.0.0' }, 'react-dom': { singleton: true, requiredVersion: '^18.0.0' }, }, }), ], };
- // webpack.config.js(主机应用/主应用) const { ModuleFederationPlugin } = require('webpack').container; module.exports = { plugins: [ new ModuleFederationPlugin({ name: 'host_app', remotes: { // 远程应用地址 remote_app: 'remote_app@https://cdn.example.com/remoteEntry.js', }, shared: { react: { singleton: true, requiredVersion: '^18.0.0' }, 'react-dom': { singleton: true, requiredVersion: '^18.0.0' }, }, }), ], };
- // host-app/src/App.tsx import React, { Suspense } from 'react'; const RemoteButton = React.lazy(() => import('remote_app/Button')); const RemoteModal = React.lazy(() => import('remote_app/Modal')); function App() { return (
- // webpack.config.js(所有子应用统一配置) const { ModuleFederationPlugin } = require('webpack').container; module.exports = { plugins: [ new ModuleFederationPlugin({ name: 'app1', filename: 'remoteEntry.js', exposes: { './Widget': './src/Widget' }, shared: { // 共享React(单例模式) react: { singleton: true, requiredVersion: '^18.0.0', import: 'react', // 优先使用主机应用的React shareKey: 'react', shareScope: 'default', }, 'react-dom': { singleton: true, requiredVersion: '^18.0.0', }, // 共享工具库 lodash: { singleton: true, import: 'lodash', }, }, }), ], };
- // webpack.config.js module.exports = { externals: { // 从CDN引入(不打包) react: 'React', 'react-dom': 'ReactDOM', lodash: '_', }, }; // HTML中引入CDN // //
- // webpack.config.js module.exports = { output: { filename: '[name].[contenthash:8].js', // 内容哈希 chunkFilename: '[name].[contenthash:8].chunk.js', }, };
- // service-worker.js const CACHE_NAME = 'micro-frontend-v1'; const urlsToCache = [ '/', '/main.abc12345.js', '/remoteButton.def67890.js', ]; // 安装事件:缓存静态资源 self.addEventListener('install', (event) => { event.waitUntil( caches.open(CACHE_NAME).then((cache) => { return cache.addAll(urlsToCache); }) ); }); // 拦截请求:缓存优先策略 self.addEventListener('fetch', (event) => { event.respondWith( caches.match(event.request).then((response) => { return response || fetch(event.request); }) ); });
- // 预加载可能需要的模块(空闲时) function preloadModule(moduleUrl: string) { const link = document.createElement('link'); link.rel = 'modulepreload'; link.href = moduleUrl; document.head.appendChild(link); } // 空闲时预加载 requestIdleCallback(() => { preloadModule('https://cdn.example.com/remote-Button.js'); preloadModule('https://cdn.example.com/remote-Modal.js'); });
- // 测量微前端加载性能 function measureMicroFrontendPerformance() { // 1. 测量TTI(Time to Interactive) const tti = performance.getEntriesByName('TTI')[0].startTime; console.log('TTI:', tti); // 2. 测量每个子应用加载时间 const remoteLoadStart = performance.mark('remote-load-start'); import('remote_app/Button').then(() => { const remoteLoadEnd = performance.mark('remote-load-end'); const duration = performance.measure( 'remote-load-duration', 'remote-load-start', 'remote-load-end' ).duration; console.log('远程模块加载时间:', duration); }); // 3. 测量FCP(First Contentful Paint) const fcp = performance.getEntriesByName('first-contentful-paint')[0].startTime; console.log('FCP:', fcp); } // 在load事件中测量 window.addEventListener('load', measureMicroFrontendPerformance);
- // 安装Sentry npm install @sentry/browser // 初始化Sentry import * as Sentry from '@sentry/browser'; Sentry.init({ dsn: 'https://examplePublicKey@o0.ingest.sentry.io/0', integrations: [ new Sentry.BrowserTracing({ tracingOrigins: ['localhost', 'example.com'], }), ], tracesSampleRate: 1.0, // 采样率(1.0 = 100%) }); // 监控微前端加载 Sentry.startTransaction({ name: 'micro-frontend-load', op: 'load', }).finish();
本文详解2026年微前端性能优化,包括Module Federation、懒加载、缓存策略等。
微前端(Micro-Frontend):
- 多个前端团队独立开发/部署
- 技术栈无关(React/Vue/Angular混合)
- 增量升级(逐步迁移)
vs 单体前端:
- 单体:所有功能打包到一个bundle(大)
- 微前端:按功能拆分(小,按需加载)
2026年趋势:
- Module Federation 2.0(Webpack 5+)
- RSC(React Server Components)
- Edge-side Includes(边缘包含)
1. 重复依赖(多个子应用都包含React)
- 网络瀑布流(串行加载多个子应用)
- 初始化阻塞(主应用等待子应用)
- 缓存失效(版本更新导致缓存失效)
// webpack.config.js(远程应用/子应用)
const { ModuleFederationPlugin } = require('webpack').container;
module.exports = {
plugins: [
new ModuleFederationPlugin({
name: 'remote_app',
filename: 'remoteEntry.js', // 远程入口文件
exposes: {
'./Button': './src/Button', // 暴露模块
'./Modal': './src/Modal',
},
shared: {
// 共享依赖(避免重复加载)
react: { singleton: true, requiredVersion: '^18.0.0' },
'react-dom': { singleton: true, requiredVersion: '^18.0.0' },
},
}),
],
};
// webpack.config.js(主机应用/主应用)
const { ModuleFederationPlugin } = require('webpack').container;
module.exports = {
plugins: [
new ModuleFederationPlugin({
name: 'host_app',
remotes: {
// 远程应用地址
remote_app: 'remote_app@https://cdn.example.com/remoteEntry.js',
},
shared: {
react: { singleton: true, requiredVersion: '^18.0.0' },
'react-dom': { singleton: true, requiredVersion: '^18.0.0' },
},
}),
],
};
// host-app/src/App.tsx
import React, { Suspense } from 'react';
const RemoteButton = React.lazy(() => import('remote_app/Button'));
const RemoteModal = React.lazy(() => import('remote_app/Modal'));
function App() {
return (
加载中...
}>

评论(0)