微前端完全教程

第一章:微前端基础

1.1 微前端概念

微前端是一种将前端应用拆分为多个独立模块的架构模式。

练习 1.1:微前端核心概念

微前端的主要特点:

1.2 微前端架构

微前端的常见架构模式。

练习 1.2:微前端架构示例

展示微前端的架构图:

微前端架构图
+------------------+
|    主应用        |
|  +------------+ |
|  | 子应用A    | |
|  +------------+ |
|  +------------+ |
|  | 子应用B    | |
|  +------------+ |
+------------------+

第二章:微前端实现方案

2.1 基于 iframe 的实现

使用 iframe 实现微前端的基本方法。

练习 2.1:iframe 实现示例

展示 iframe 实现微前端的代码:

iframe 实现代码
<!-- 主应用 HTML -->
<div class="micro-app-container">
  <iframe 
    src="http://sub-app.com" 
    frameborder="0"
    width="100%"
    height="100%"
  ></iframe>
</div>

2.2 基于 Web Components 的实现

使用 Web Components 实现微前端。

练习 2.2:Web Components 实现示例

展示 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);

第三章:微前端框架

3.1 qiankun 框架

使用 qiankun 实现微前端。

练习 3.1: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('子应用卸载');
}

3.2 single-spa 框架

使用 single-spa 实现微前端。

练习 3.2:single-spa 实现示例

展示 single-spa 实现微前端的代码:

single-spa 配置
// 主应用
import { registerApplication, start } from 'single-spa';

registerApplication({
  name: 'sub-app',
  app: () => System.import('sub-app'),
  activeWhen: '/sub-app'
});

start();

第四章:微前端最佳实践

4.1 样式隔离

微前端中的样式隔离方案。

练习 4.1:样式隔离示例

展示样式隔离的实现:

CSS 隔离方案
/* 使用 CSS Modules */
.subApp {
  composes: container from './styles.css';
}

/* 使用 Shadow DOM */
:host {
  display: block;
  --primary-color: #42b983;
}

/* 使用命名空间 */
.sub-app-container {
  /* 子应用样式 */
}

4.2 状态管理

微前端中的状态管理方案。

练习 4.2:状态管理示例

展示状态管理的实现:

状态管理方案
// 使用发布订阅模式
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);
});

学习建议

建议按照章节顺序学习,每完成一个练习后再进行下一个。可以通过实际项目来实践所学知识,特别是微前端框架和最佳实践部分。注意微前端的实现方案需要根据项目需求选择合适的方案。