簡介
Shell應用程式(容器應用程式)是整個微前端的協調大腦。它決定佈局、路由、身份驗證以及 MFE 之間的通訊方式。

1. Shell 應用程式職責
Shell Application:
├── Layout Management (Header, Footer, Sidebar)
├── Routing Orchestration (top-level routes → MFE)
├── Authentication (Login/Logout, token management)
├── Shared Services (Event Bus, Error Boundary)
└── Performance (Lazy loading, prefetching)
2. 路由架構
2.1 路由所有權
每個 MFE 都有自己的路由,shell 僅委託:
function ShellRoutes() {
return (
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/products/*" element={
<MFELoader name="product" module="./ProductRoutes" />
} />
<Route path="/cart/*" element={
<MFELoader name="cart" module="./CartRoutes" />
} />
<Route path="/orders/*" element={
<MFELoader name="order" module="./OrderRoutes" />
} />
<Route path="*" element={<NotFound />} />
</Routes>
);
}
2.2 MFE內部路由
// Product MFE - own routes
function ProductRoutes() {
return (
<Routes>
<Route index element={<ProductList />} />
<Route path=":id" element={<ProductDetail />} />
<Route path="category/:slug" element={<CategoryPage />} />
</Routes>
);
}
3.佈局架構
┌─────────────────────────────────────────────┐
│ Shell App │
│ ┌─────────────────────────────────────────┐ │
│ │ Header (Shell-owned) │ │
│ │ Logo │ Nav │ Search │ Cart │ User │ │ │
│ ├─────┬───────────────────────────────────┤ │
│ │Side │ ┌─────────────────────────────┐ │ │
│ │bar │ │ MFE Content Area │ │ │
│ │ │ │ (dynamic, loaded by route) │ │ │
│ │ │ └─────────────────────────────┘ │ │
│ ├─────┴───────────────────────────────────┤ │
│ │ Footer (Shell-owned) │ │
│ └─────────────────────────────────────────┘ │
└─────────────────────────────────────────────┘
Shell 管理:頁首、頁尾、側邊欄、載入、錯誤邊界 MFE管理:內容區、內部路由、本機狀態
4. 身份驗證集成
Shell handles login → broadcasts auth state to MFEs:
Shell App ──login──► Keycloak (OIDC)
Shell App ◄──tokens── Keycloak
Shell App ═══broadcast══► MFE A (useAuth())
Shell App ═══broadcast══► MFE B (useAuth())
function Shell() {
const auth = useKeycloakAuth();
return (
<AuthContext.Provider value={auth}>
<Header user={auth.user} />
<Suspense fallback={<Loading />}>
<Outlet />
</Suspense>
</AuthContext.Provider>
);
}
5. 績效策略
5.1 延遲載入+預取
function NavLink({ to, mfeName, children }) {
const handleMouseEnter = () => {
import(/* webpackPrefetch: true */ `${mfeName}/Routes`);
};
return <Link to={to} onMouseEnter={handleMouseEnter}>{children}</Link>;
}
5.2 績效預算
Per MFE limits:
├── JavaScript: max 250KB gzipped
├── CSS: max 50KB gzipped
├── First Contentful Paint: < 1.5s
├── Time to Interactive: < 3s
└── Lighthouse Score: > 80
總結
- Shell = 協調器 — 擁有佈局、路由、身份驗證
- 每個MFE擁有內容區域和內部路線
- 由 Shell 處理的身份驗證,廣播到 MFE
- Shell 必須薄 — 不包含業務邏輯
下一篇文章: 第 14 課:跨 MFE 狀態管理與通信