Chuyển tới nội dung chính

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:

  • build riêng (Vite config riêng, Dockerfile riêng)
  • dev server riêng (port riêng)
  • Expose 1 remote entry (RemoteApp component)
  • Import shared dependencies dạng singleton (React, Router, Redux)

Container Host

apps/container/host application — chịu trách nhiệm:

  1. Load MFE qua Module Federation
  2. Routingroutes.config.ts định nghĩa tất cả routes
  3. Auth Guard — kiểm tra authentication & authorization
  4. Layout — Sidebar, Header, Main content area
  5. Error HandlingMfeErrorBoundary bắt lỗi MFE crash

MFE Registry

Tất cả MFE được đăng ký trong mfeRegistry.tsnguồ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.js trự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):

PackageStrategyLý do
reactsingletonContext, hooks phải cùng instance
react-domsingletonDOM rendering
react-router-domsingletonRouting context
react-reduxsingletonStore 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.