Micro frontends: How to brew a pot of "divide and conquer" Kung Fu tea?
Micro frontends are like brewing a pot of Gongfu tea, embodying the philosophy of "divide and conquer." Each tea utensil has its own role—teapot, teacup, tea strainer—each with clear responsibilities, yet harmoniously unified. Similarly, frontend architecture breaks down monolithic applications into independent modules, enabling standalone development and deployment while seamlessly integrating.
Why Micro Frontends?
Traditional monolithic frontends are like a large teapot where all tea leaves (code) are mixed together. As the business grows, the leaves pile up, eventually making the brew murky and undrinkable. Micro frontends, on the other hand, package different tea leaves into small sachets for on-demand brewing:
- Tech Stack Agnostic: React, Vue, and Angular are like black tea, green tea, and oolong tea—they can coexist on the same tea tray.
- Independent Deployment: Each tea sachet can be replaced individually without affecting others.
- Progressive Upgrades: Legacy projects are like aged pu-erh tea—no need to discard and rebrew the entire pot.
// Monolithic app vs. micro frontends
monolithicApp = {
header: 'React',
body: 'Angular', // Tech stack conflict!
footer: 'Vue'
};
microFrontends = [
{ name: 'header', tech: 'React', version: '18' },
{ name: 'body', tech: 'Angular', version: '15' }, // Peaceful coexistence
{ name: 'footer', tech: 'Vue', version: '3' }
];
Six Tea Ceremony Techniques for Micro Frontends
Route Distribution: The Art of Tea Allocation
Assign different micro-apps to different URL paths, like serving tea based on guests' preferences:
// Main app route configuration
const routes = [
{
path: '/tea-shop/*',
loadComponent: () => import('tea-shop-microapp')
},
{
path: '/tea-farm/*',
loadComponent: () => import('tea-farm-microapp')
}
];
Module Federation: The Art of Tea Blending
Webpack 5's Module Federation allows sharing dependencies across apps, like blending teas for unique flavors:
// Host configuration (tea-host)
new ModuleFederationPlugin({
name: 'host',
remotes: {
shop: 'shop@http://cdn.example.com/shop-remote-entry.js',
farm: 'farm@http://cdn.example.com/farm-remote-entry.js'
},
shared: ['react', 'react-dom'] // Shared base libraries
});
iframe Encapsulation: Tea Sachets in a Clay Teapot
An ancient but effective isolation method, ideal for strong sandboxing:
<iframe
src="https://microapp.example.com"
style="width: 100%; border: none"
sandbox="allow-scripts allow-same-origin"
></iframe>
Web Components: Modern Tea Utensil Standards
Browser-native component model, no extra frameworks needed:
class TeaShopElement extends HTMLElement {
connectedCallback() {
this.innerHTML = `<div class="tea-shop">...</div>`;
// Dynamically load micro-app resources
const script = document.createElement('script');
script.src = 'https://microapp.example.com/main.js';
this.appendChild(script);
}
}
customElements.define('tea-shop', TeaShopElement);
Micro Frontend Communication: Secret Signals at the Tea Table
Use CustomEvent for cross-app communication:
// Publish an event (tea master signals)
document.dispatchEvent(
new CustomEvent('tea-ready', {
detail: { type: 'oolong', temperature: 85 }
})
);
// Subscribe to event (tea guest receives signal)
document.addEventListener('tea-ready', (e) => {
console.log(`Received ${e.detail.type} tea, optimal temperature ${e.detail.temperature}°C`);
});
CSS Isolation: Preventing Flavor Mixing
Use Shadow DOM or CSS namespaces to avoid style pollution:
/* BEM naming convention */
.tea-shop__header--primary {
color: #8B4513; /* Tea brew color */
}
/* Shadow DOM style encapsulation */
const shadow = element.attachShadow({ mode: 'open' });
shadow.innerHTML = `
<style>
h1 { font-family: 'KaiTi', serif; }
</style>
<h1>Micro Frontend Tea Ceremony</h1>
`;
Micro Frontend Tasting Guide
Clarity of the Brew (Performance Optimization)
-
Lazy Loading: Like pouring water in stages, avoid loading all resources at once.
// Dynamically load micro-apps const loadMicroApp = async (name) => { await import(`./microapps/${name}.js`); mountMicroApp(name); };
-
Dependency Sharing: Multiple teapots sharing the same heat source (shared third-party libraries).
// Module Federation shared configuration "shared": { "lodash": { "singleton": true, "requiredVersion": "^4.17.0" } }
Layered Aroma (State Management)
Use pub-sub pattern for global state management:
// Tea room state hub
class TeaState {
private subscribers: Function[] = [];
subscribe(callback: (state: any) => void) {
this.subscribers.push(callback);
}
update(newState: any) {
this.subscribers.forEach(fn => fn(newState));
}
}
// Micro-apps share the same state instance
const globalTeaState = new TeaState();
Taboos of Micro Frontend Tea Ceremony
-
Over-Splitting: Like shredding tea leaves into powder, losing the essence.
- Advice: Divide by business domain (products, orders, users, etc.).
-
Ignoring Monitoring: Unaware of失控的茶温 (out-of-control tea temperature).
// Unified error monitoring window.addEventListener('error', (e) => { sendToMonitoring({ app: getCurrentMicroAppName(), error: e.message }); });
-
Style Conflicts: Mixing different tea brews in one cup.
- Solutions: CSS-in-JS or Shadow DOM.
From Tea Art to Engineering
Build a complete micro frontend tea ceremony workflow:
graph TD
A[Independent Dev] -->|Git Submodule| B(Version Control)
B --> C{CI/CD Pipeline}
C -->|Auto Build| D[Container Image]
C -->|Independent Deploy| E[CDN Distribution]
D --> F[Runtime Integration]
E --> F
F --> G[User Access]
Recommended tools:
- Tea Utensils: Single-SPA, Qiankun, Piral
- Water Quality Check: Lighthouse, WebPageTest
- Tea Table Setup: Nginx routing, Kubernetes Ingress
The Future Aroma of Micro Frontends
- Module Federation 2.0: Vite ecosystem's hot module reloading.
- Edge Computing: Bringing the tea table closer to users (CDN edge deployment).
- WebAssembly: High-performance tea ceremony (complex computation scenarios).
// Future micro frontend core logic may be written in Rust
#[wasm_bindgen]
pub fn brew_tea(tea_type: String) -> String {
format!("Brewed {} tea", tea_type)
}
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn