Micro-Frontend & Module Federation
Tổng quan
Hệ thống sử dụng Vite Module Federation (@module-federation/vite) để tách ứng dụng thành nhiều MFE độc lập. Mỗi MFE:
- Có build riêng (Vite config riêng, Dockerfile riêng)
- Có dev server riêng (port riêng)
- Expose 1 remote entry (
RemoteAppcomponent) - Import shared dependencies dạng singleton (React, Router, Redux)
Container Host
apps/container/ là host application — chịu trách nhiệm:
- Load MFE qua Module Federation
- Routing —
routes.config.tsđịnh nghĩa tất cả routes - Auth Guard — kiểm tra authentication & authorization
- Layout — Sidebar, Header, Main content area
- Error Handling —
MfeErrorBoundarybắt lỗi MFE crash
MFE Registry
Tất cả MFE được đăng ký trong mfeRegistry.ts — nguồn dữ liệu duy nhất:
export const MFE_REGISTRY = {
auth: { name: "auth", devPort: 8082, basePath: "/auth" },
dashboard: { name: "dashboard", devPort: 8081, basePath: "/dashboard" },
inventory: { name: "inventory", devPort: 8084, basePath: "/inventory" },
content: { name: "content", devPort: 8083, basePath: "/content" },
// ... tất cả MFEs
};
Vite Config (Container)
// apps/container/vite.config.ts
federation({
name: "container",
remotes: generateRemotes(process.env), // Từ MFE_REGISTRY
shared: {
react: { singleton: true },
"react-dom": { singleton: true },
"react-router-dom": { singleton: true },
"react-redux": { singleton: true },
},
});
Remote MFE
Mỗi MFE expose 1 RemoteApp component:
// apps/<module>/src/RemoteApp.tsx
export default function RemoteApp() {
// Sync token & URL từ container
useTokenSync();
useUrlSync();
return (
<Provider store={store}>
<Routes>
{/* Internal routes */}
</Routes>
</Provider>
);
}
Vite Config (Remote)
// apps/<module>/vite.config.ts
federation({
name: "<module-name>",
exposes: {
"./RemoteApp": "./src/RemoteApp.tsx",
},
shared: {
react: { singleton: true },
"react-dom": { singleton: true },
"react-router-dom": { singleton: true },
"react-redux": { singleton: true },
},
});
Luồng load MFE
Development vs Production
Development
- Container proxy forwards requests tới MFE dev servers:
/inventory/*→localhost:8084/auth/*→localhost:8082
- MFE dev servers serve
remoteEntry.jstrực tiếp
Production
- Mỗi MFE build thành static files → Docker image → K8s pod
- Nginx reverse proxy forward theo path
REMOTE_*env vars cho phép override entry URLs
Shared Dependencies
Các dependencies sau được share giữa Container và MFEs (chỉ load 1 lần):
| Package | Strategy | Lý do |
|---|---|---|
react | singleton | Context, hooks phải cùng instance |
react-dom | singleton | DOM rendering |
react-router-dom | singleton | Routing context |
react-redux | singleton | Store context |
cảnh báo
Không thêm shared dependency mà không cân nhắc kỹ. Mỗi shared dep tăng coupling giữa các MFEs.