10 tháng 12, 2025 · 11 phút đọc

Micro-frontends với Module Federation: khi nào nên và không nên dùng

Module Federation cho phép chia sẻ code runtime giữa independent deployments — giải pháp mạnh nhưng đi kèm với complexity cao.

Micro-frontends với Module Federation: khi nào nên và không nên dùng

Micro-frontends là architectural pattern chia frontend monolith thành independent deployable units. Module Federation (Webpack 5 feature) là implementation phổ biến nhất cho JavaScript. Nhưng complexity đi kèm rất đáng kể — đừng adopt chỉ vì 'microservices cool'.

Khi nào Micro-frontends có nghĩa?

Phù hợp khi: (1) nhiều teams độc lập muốn deploy independently, (2) legacy migration — dần dần thay thế legacy app bằng modern components, (3) different tech stacks trong cùng một product (React + Angular). Không phù hợp cho team nhỏ hoặc monorepo đã giải quyết được code sharing.

Multiple teams working on separate screens
Micro-frontends phù hợp nhất khi có nhiều teams với release cycles độc lập

Module Federation Architecture

Host application: shell app load remote modules runtime. Remote applications: expose components/modules cho host consume. Shared dependencies: React, React DOM được singleton để tránh multiple instances. Version negotiation tự động theo semver.

Challenges thực tế

Shared state phức tạp: remotes không share React context với host. Routing coordination: deep links, nested routes. CSS isolation: styles có thể leak giữa remotes. Type safety: TypeScript types không tự động share — cần publish type packages hoặc dùng type federation tools.

Testing Strategy

Test remotes independently với mock host. Integration tests với contract testing (Pact). E2E tests với composed application. CI/CD cần orchestrate deployment order nếu có breaking changes trong shared interfaces.

Alternatives

Trước khi dùng Module Federation, xem xét: monorepo với Turborepo (simpler, same benefits for most teams), iframe-based isolation (simple but limited), Web Components (framework-agnostic but verbose). Micro-frontends là engineering trade-off, không phải silver bullet.