微前端是一种将前端应用拆分为多个独立模块的架构模式。
微前端的主要特点:
微前端的常见架构模式。
展示微前端的架构图:
+------------------+
| 主应用 |
| +------------+ |
| | 子应用A | |
| +------------+ |
| +------------+ |
| | 子应用B | |
| +------------+ |
+------------------+
使用 iframe 实现微前端的基本方法。
展示 iframe 实现微前端的代码:
<!-- 主应用 HTML -->
<div class="micro-app-container">
<iframe
src="http://sub-app.com"
frameborder="0"
width="100%"
height="100%"
></iframe>
</div>
使用 Web Components 实现微前端。
展示 Web Components 实现微前端的代码:
// 子应用
class MicroApp extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
}
connectedCallback() {
this.render();
}
render() {
this.shadowRoot.innerHTML = `
<style>
:host {
display: block;
}
</style>
<div>
<h1>子应用内容</h1>
</div>
`;
}
}
customElements.define('micro-app', MicroApp);
使用 qiankun 实现微前端。
展示 qiankun 实现微前端的代码:
// 主应用
import { registerMicroApps, start } from 'qiankun';
registerMicroApps([
{
name: 'sub-app',
entry: '//localhost:7100',
container: '#subapp-viewport',
activeRule: '/sub-app',
}
]);
start();
// 子应用
import { registerMicroApps } from 'qiankun';
export async function bootstrap() {
console.log('子应用启动');
}
export async function mount(props) {
console.log('子应用挂载');
render(props);
}
export async function unmount() {
console.log('子应用卸载');
}
使用 single-spa 实现微前端。
展示 single-spa 实现微前端的代码:
// 主应用
import { registerApplication, start } from 'single-spa';
registerApplication({
name: 'sub-app',
app: () => System.import('sub-app'),
activeWhen: '/sub-app'
});
start();
微前端中的样式隔离方案。
展示样式隔离的实现:
/* 使用 CSS Modules */
.subApp {
composes: container from './styles.css';
}
/* 使用 Shadow DOM */
:host {
display: block;
--primary-color: #42b983;
}
/* 使用命名空间 */
.sub-app-container {
/* 子应用样式 */
}
微前端中的状态管理方案。
展示状态管理的实现:
// 使用发布订阅模式
class EventBus {
constructor() {
this.events = {};
}
on(event, callback) {
if (!this.events[event]) {
this.events[event] = [];
}
this.events[event].push(callback);
}
emit(event, data) {
if (this.events[event]) {
this.events[event].forEach(callback => callback(data));
}
}
}
// 使用
const eventBus = new EventBus();
eventBus.on('user-login', (user) => {
console.log('用户登录:', user);
});
建议按照章节顺序学习,每完成一个练习后再进行下一个。可以通过实际项目来实践所学知识,特别是微前端框架和最佳实践部分。注意微前端的实现方案需要根据项目需求选择合适的方案。