工程化与框架系列(10)--微前端架构

微前端架构 🏗️

微前端是一种将前端应用分解成更小、更易管理的独立部分的架构模式。本文将详细介绍微前端的核心概念、实现方案和最佳实践。

微前端概述 🌟

💡 小知识:微前端的核心理念是将前端应用分解成一系列独立部署、松耦合的小型应用,每个应用可以由不同的团队使用不同的技术栈开发。

为什么需要微前端

在大型前端应用开发中,微前端架构能带来以下优势:

  1. 技术栈灵活性

    • 支持多框架共存
    • 渐进式技术迁移
    • 团队技术选择自由
    • 复用已有应用资产
  2. 团队自主性

    • 独立开发部署
    • 团队边界清晰
    • 降低协作成本
    • 提高开发效率
  3. 应用可维护性

    • 代码库规模可控
    • 模块职责单一
    • 降低耦合度
    • 简化测试和部署
  4. 性能优化空间

    • 按需加载应用
    • 独立缓存策略
    • 资源并行加载
    • 性能瓶颈隔离

实现方案详解 ⚡

基于路由的实现

// router-based.ts
interface MicroApp {name: string;entry: string;container: string;activeRule: string;
}export class RouterBasedMicroFrontend {private apps: MicroApp[] = [];constructor(apps: MicroApp[]) {this.apps = apps;this.initializeRouter();}private initializeRouter(): void {window.addEventListener('popstate', () => {this.handleRouteChange();});// 初始化时加载匹配的应用this.handleRouteChange();}private handleRouteChange(): void {const path = window.location.pathname;const app = this.apps.find(app => path.startsWith(app.activeRule));if (app) {this.loadApp(app);}}private async loadApp(app: MicroApp): Promise<void> {try {// 加载应用资源const html = await this.fetchAppHTML(app.entry);const container = document.querySelector(app.container);if (container) {container.innerHTML = html;this.executeAppScripts(app);}} catch (error) {console.error(`Failed to load app ${app.name}:`, error);}}private async fetchAppHTML(entry: string): Promise<string> {const response = await fetch(entry);return await response.text();}private executeAppScripts(app: MicroApp): void {// 执行应用脚本// 这里需要处理JS隔离等问题}
}// 使用示例
const microFrontend = new RouterBasedMicroFrontend([{name: 'app1',entry: 'http://localhost:3001',container: '#app1-container',activeRule: '/app1'},{name: 'app2',entry: 'http://localhost:3002',container: '#app2-container',activeRule: '/app2'}
]);

基于Web Components的实现

// web-components.ts
interface WebComponentApp {name: string;element: string;url: string;
}export class WebComponentMicroFrontend {constructor(apps: WebComponentApp[]) {this.registerApps(apps);}private registerApps(apps: WebComponentApp[]): void {apps.forEach(app => {this.defineCustomElement(app);});}private async defineCustomElement(app: WebComponentApp): Promise<void> {class MicroApp extends HTMLElement {private shadow: ShadowRoot;constructor() {super();this.shadow = this.attachShadow({ mode: 'open' });}async connectedCallback() {try {const content = await this.loadAppContent(app.url);this.shadow.innerHTML = content;await this.executeScripts();} catch (error) {console.error(`Failed to load ${app.name}:`, error);}}private async loadAppContent(url: string): Promise<string> {const response = await fetch(url);return await response.text();}private async executeScripts(): Promise<void> {// 执行应用脚本,确保在Shadow DOM上下文中运行}}customElements.define(app.element, MicroApp);}
}// 使用示例
const webComponentMicro = new WebComponentMicroFrontend([{name: 'app1',element: 'micro-app1',url: 'http://localhost:3001/app1'},{name: 'app2',element: 'micro-app2',url: 'http://localhost:3002/app2'}
]);

通信机制实现 🔄

事件总线

// event-bus.ts
type EventHandler = (data: any) => void;export class EventBus {private static instance: EventBus;private events: Map<string, EventHandler[]>;private constructor() {this.events = new Map();}public static getInstance(): EventBus {if (!EventBus.instance) {EventBus.instance = new EventBus();}return EventBus.instance;}public on(event: string, handler: EventHandler): void {if (!this.events.has(event)) {this.events.set(event, []);}this.events.get(event)!.push(handler);}public off(event: string, handler: EventHandler): void {if (!this.events.has(event)) return;const handlers = this.events.get(event)!;const index = handlers.indexOf(handler);if (index > -1) {handlers.splice(index, 1);}}public emit(event: string, data: any): void {if (!this.events.has(event)) return;this.events.get(event)!.forEach(handler => {try {handler(data);} catch (error) {console.error(`Error in event handler for ${event}:`, error);}});}
}// 使用示例
const eventBus = EventBus.getInstance();// 在应用A中订阅事件
eventBus.on('userLogin', (user) => {console.log('User logged in:', user);
});// 在应用B中触发事件
eventBus.emit('userLogin', { id: 1, name: 'John Doe' 
});

状态共享

// shared-state.ts
interface StateChangeListener<T> {(newState: T, oldState: T): void;
}export class SharedState<T extends object> {private state: T;private listeners: StateChangeListener<T>[] = [];constructor(initialState: T) {this.state = new Proxy(initialState, {set: (target, property, value) => {const oldState = { ...this.state };target[property as keyof T] = value;this.notifyListeners(this.state, oldState);return true;}});}public getState(): T {return this.state;}public setState(partial: Partial<T>): void {const oldState = { ...this.state };Object.assign(this.state, partial);this.notifyListeners(this.state, oldState);}public subscribe(listener: StateChangeListener<T>): () => void {this.listeners.push(listener);return () => {const index = this.listeners.indexOf(listener);if (index > -1) {this.listeners.splice(index, 1);}};}private notifyListeners(newState: T, oldState: T): void {this.listeners.forEach(listener => {try {listener(newState, oldState);} catch (error) {console.error('Error in state change listener:', error);}});}
}// 使用示例
interface UserState {isLoggedIn: boolean;user: {id: number;name: string;} | null;
}const sharedState = new SharedState<UserState>({isLoggedIn: false,user: null
});// 在应用A中订阅状态变化
sharedState.subscribe((newState, oldState) => {console.log('State changed:', { newState, oldState });
});// 在应用B中更新状态
sharedState.setState({isLoggedIn: true,user: {id: 1,name: 'John Doe'}
});

样式隔离方案 🎨

CSS Module Federation

// style-isolation.ts
interface StyleConfig {prefix: string;scope: string;
}export class StyleIsolation {private config: StyleConfig;constructor(config: StyleConfig) {this.config = config;this.initializeStyleIsolation();}private initializeStyleIsolation(): void {// 添加样式作用域document.documentElement.setAttribute('data-app-scope',this.config.scope);// 处理动态添加的样式this.observeStyleChanges();}private observeStyleChanges(): void {const observer = new MutationObserver((mutations) => {mutations.forEach(mutation => {mutation.addedNodes.forEach(node => {if (node instanceof HTMLStyleElement) {this.processStyle(node);}});});});observer.observe(document.head, {childList: true});}private processStyle(styleElement: HTMLStyleElement): void {const css = styleElement.textContent || '';const scopedCss = this.scopeCSS(css);styleElement.textContent = scopedCss;}private scopeCSS(css: string): string {// 为所有选择器添加作用域前缀return css.replace(/([^}]*){/g, (match) => {return match.split(',').map(selector => `[data-app-scope="${this.config.scope}"] ${selector.trim()}`).join(',');});}
}// 使用示例
const styleIsolation = new StyleIsolation({prefix: 'app1',scope: 'micro-app1'
});

性能优化策略 ⚡

资源加载优化

// resource-loader.ts
interface ResourceConfig {js: string[];css: string[];prefetch?: string[];
}export class ResourceLoader {private loadedResources: Set<string> = new Set();private loading: Map<string, Promise<void>> = new Map();public async loadApp(config: ResourceConfig): Promise<void> {try {// 并行加载JS和CSS资源await Promise.all([this.loadJSResources(config.js),this.loadCSSResources(config.css)]);// 预加载其他资源if (config.prefetch) {this.prefetchResources(config.prefetch);}} catch (error) {console.error('Failed to load resources:', error);throw error;}}private async loadJSResources(urls: string[]): Promise<void> {const promises = urls.map(url => this.loadJS(url));await Promise.all(promises);}private async loadCSSResources(urls: string[]): Promise<void> {const promises = urls.map(url => this.loadCSS(url));await Promise.all(promises);}private async loadJS(url: string): Promise<void> {if (this.loadedResources.has(url)) {return;}if (this.loading.has(url)) {return this.loading.get(url);}const promise = new Promise<void>((resolve, reject) => {const script = document.createElement('script');script.src = url;script.async = true;script.onload = () => {this.loadedResources.add(url);this.loading.delete(url);resolve();};script.onerror = () => {this.loading.delete(url);reject(new Error(`Failed to load script: ${url}`));};document.head.appendChild(script);});this.loading.set(url, promise);return promise;}private async loadCSS(url: string): Promise<void> {if (this.loadedResources.has(url)) {return;}return new Promise((resolve, reject) => {const link = document.createElement('link');link.rel = 'stylesheet';link.href = url;link.onload = () => {this.loadedResources.add(url);resolve();};link.onerror = () => {reject(new Error(`Failed to load CSS: ${url}`));};document.head.appendChild(link);});}private prefetchResources(urls: string[]): void {urls.forEach(url => {if (!this.loadedResources.has(url)) {const link = document.createElement('link');link.rel = 'prefetch';link.href = url;document.head.appendChild(link);}});}
}

最佳实践建议 ⭐

应用设计原则

  1. 独立性原则

    • 应用间松耦合
    • 独立开发部署
    • 运行时隔离
    • 故障隔离
  2. 统一规范

    • 通信协议标准
    • 路由管理规范
    • 样式命名规范
    • 错误处理机制
  3. 性能优化

    • 按需加载策略
    • 资源复用机制
    • 缓存优化方案
    • 预加载策略

开发流程建议

  1. 项目初始化
# 创建微前端项目结构
mkdir micro-frontend && cd micro-frontend
mkdir container app1 app2 shared# 初始化基座应用
cd container
npm init -y
npm install @micro-frontend/core# 初始化子应用
cd ../app1
npm init -y
npm install @micro-frontend/app
  1. 开发规范
// 子应用生命周期规范
interface MicroAppLifecycle {bootstrap(): Promise<void>;mount(props: Record<string, any>): Promise<void>;unmount(): Promise<void>;
}// 实现示例
export class MicroApp implements MicroAppLifecycle {async bootstrap(): Promise<void> {// 应用初始化}async mount(props: Record<string, any>): Promise<void> {// 应用挂载}async unmount(): Promise<void> {// 应用卸载}
}

结语 📝

微前端架构为大型前端应用开发提供了一种可扩展、可维护的解决方案。通过本文,我们学习了:

  1. 微前端的核心概念和价值
  2. 不同的实现方案及其特点
  3. 应用间通信机制的实现
  4. 样式隔离和资源加载优化
  5. 微前端的最佳实践和建议

💡 学习建议:

  1. 从小规模试点开始,逐步扩大应用范围
  2. 注重基础设施和工具链建设
  3. 建立完善的开发规范和文档
  4. 重视性能优化和用户体验
  5. 保持技术栈的适度统一

如果你觉得这篇文章有帮助,欢迎点赞收藏,也期待在评论区看到你的想法和建议!👇

终身学习,共同成长。

咱们下一期见

💻

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/web/71160.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

SwiftUI之状态管理全解析

文章目录 引言一、`@State`1.1 基本概念1.2 初始化与默认值1.3 注意事项二、`@Binding`2.1 基本概念2.2 初始化与使用2.3 注意事项三、`@ObservedObject`3.1 基本概念3.2 初始化与使用3.3 注意事项四、`@EnvironmentObject`4.1 基本概念4.2 初始化与使用4.3 注意事项五、`@Stat…

Redis 高可用性:如何让你的缓存一直在线,稳定运行?

&#x1f3af; 引言&#xff1a;Redis的高可用性为啥这么重要&#xff1f; 在现代高可用系统中&#xff0c;Redis 是一款不可或缺的分布式缓存与数据库系统。无论是提升访问速度&#xff0c;还是实现数据的高效持久化&#xff0c;Redis 都能轻松搞定。可是&#xff0c;当你把 …

面试题:说一下你对DDD的了解?

面试题:说一下你对DDD的了解? 在面试中,关于 DDD(领域驱动设计,Domain-Driven Design) 的问题是一个常见的技术考察点。DDD 是一种软件设计方法论,旨在通过深入理解业务领域来构建复杂的软件系统。以下是一个清晰、详细的回答模板,帮助你在面试中脱颖而出: DDD 的定义…

Redis---缓存穿透,雪崩,击穿

文章目录 缓存穿透什么是缓存穿透&#xff1f;缓存穿透情况的处理流程是怎样的&#xff1f;缓存穿透的解决办法缓存无效 key布隆过滤器 缓存雪崩什么是缓存雪崩&#xff1f;缓存雪崩的解决办法 缓存击穿什么是缓存击穿&#xff1f;缓存击穿的解决办法 区别对比 在如今的开发中&…

Android Logcat 高效调试指南

工具概览 Logcat 是 Android SDK 提供的命令行日志工具&#xff0c;支持灵活过滤、格式定制和实时监控&#xff0c;官方文档详见 Android Developer。 基础用法 命令格式 [adb] logcat [<option>] ... [<filter-spec>] ... 执行方式 直接调用&#xff08;通过ADB守…

【定昌Linux系统】部署了java程序,设置开启启动

将代码上传到相应的目录&#xff0c;并且配置了一个.sh的启动脚本文件 文件内容&#xff1a; #!/bin/bash# 指定JAR文件的路径&#xff08;如果JAR文件在当前目录&#xff0c;可以直接使用文件名&#xff09; JAR_FILE"/usr/local/java/xs_luruan_client/lib/xs_luruan_…

Java 8 中,可以使用 Stream API 和 Comparator 对 List 按照元素对象的时间字段进行倒序排序

文章目录 引言I 示例对象II List 按时间字段倒序排序: 使用 `Stream` 和 `Comparator` 排序方法 1:使用 `Comparator.comparing`方法 2:使用 `Comparator.reversed`方法 3:自定义 `Comparator`输出结果III 注意事项**时间字段类型**:**空值处理**:IV 总结引言 案例:在线用…

jvm内存模型,类加载机制,GC算法,垃圾回收器,jvm线上调优等常见的面试题及答案

JVM内存模型 JVM内存模型包括哪些区域 答案&#xff1a;JVM内存模型主要包括以下区域&#xff1a; 程序计数器&#xff1a;是一块较小的内存空间&#xff0c;它可以看作是当前线程所执行的字节码的行号指示器&#xff0c;用于记录正在执行的虚拟机字节码指令的地址。Java虚拟机…

git clone的时候出现出现error

报错如下&#xff1a; Collecting githttps://github.com/haotian-liu/LLaVA.git Cloning https://github.com/haotian-liu/LLaVA.git to /tmp/pip-req-build-360q6tt1 Running command git clone --filterblob:none --quiet https://github.com/haotian-liu/LLaVA.git /t…

Minio搭建并在SpringBoot中使用完成用户头像的上传

Minio使用搭建并上传用户头像到服务器操作,学习笔记 Minio介绍 minio官网 MinIO是一个开源的分布式对象存储服务器&#xff0c;支持S3协议并且可以在多节点上实现数据的高可用和容错。它采用Go语言开发&#xff0c;拥有轻量级、高性能、易部署等特点&#xff0c;并且可以自由…

vue3中ref和reactive响应式数据、ref模板引用(组合式和选项式区别)、组件ref的使用

目录 Ⅰ.ref 1.基本用法&#xff1a;ref响应式数据 2.ref模板引用 3.ref在v-for中的模板引用 ​4.ref在组件上使用 ​5.TS中ref数据标注类型 Ⅱ.reactive 1.基本用法&#xff1a;reactive响应式数据 2.TS中reactive标注类型 Ⅲ.ref和reactive的使用场景和区别 Ⅳ.小结…

javascript实现雪花飘落效果

本文实现雪花飘落效果的 JavaScript 网页设计案例&#xff0c;代码实现如下&#xff1a; <!DOCTYPE html> <html lang"en"><head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-width, init…

项目准备(flask+pyhon+MachineLearning)- 3

目录 1.商品信息 2. 商品销售预测 2.1 机器学习 2.2 预测功能 3. 模型评估 1.商品信息 app.route(/products) def products():"""商品分析页面"""data load_data()# 计算当前期间和上期间current_period data[data[成交时间] > data[成…

FPGA开发,使用Deepseek V3还是R1(3):系统级与RTL级

以下都是Deepseek生成的答案 FPGA开发&#xff0c;使用Deepseek V3还是R1&#xff08;1&#xff09;&#xff1a;应用场景 FPGA开发&#xff0c;使用Deepseek V3还是R1&#xff08;2&#xff09;&#xff1a;V3和R1的区别 FPGA开发&#xff0c;使用Deepseek V3还是R1&#x…

实现 Leaflet 多类型点位标记与聚合功能的实战经验分享

在现代的地理信息系统&#xff08;GIS&#xff09;应用中&#xff0c;地图功能是不可或缺的一部分。无论是展示商业网点、旅游景点还是公共服务设施&#xff0c;地图都能以直观的方式呈现数据。然而&#xff0c;当数据量较大时&#xff0c;地图上可能会出现大量的标记点&#x…

企微审批中MySQL字段TEXT类型被截断的排查与修复实践

在MySQL中&#xff0c;TEXT类型字段常用于存储较大的文本数据&#xff0c;但在一些应用场景中&#xff0c;当文本内容较大时&#xff0c;TEXT类型字段可能无法满足需求&#xff0c;导致数据截断或插入失败。为了避免这种问题&#xff0c;了解不同文本类型&#xff08;如TEXT、M…

【常见BUG】Spring Boot 和 Springfox(Swagger)版本兼容问题

???欢迎来到我的博客&#xff0c;很高兴能够在这里和您见面&#xff01;希望您在这里可以感受到一份轻松愉快的氛围&#xff0c;不仅可以获得有趣的内容和知识&#xff0c;也可以畅所欲言、分享您的想法和见解。 推荐:kwan 的首页,持续学习,不断总结,共同进步,活到老学到老…

HTTP 协议的发展历程:从 HTTP/1.0 到 HTTP/2.0

HTTP 协议的发展历程&#xff1a;从 HTTP/1.0 到 HTTP/2.0 HTTP&#xff08;HyperText Transfer Protocol&#xff0c;超文本传输协议&#xff09;是 Web 的基础协议&#xff0c;用于客户端和服务器之间的通信。从 HTTP/1.0 到 HTTP/2.0&#xff0c;HTTP 协议经历了多次重大改…

apload-lab打靶场

1.提示显示所以关闭js 上传<?php phpinfo(); ?>的png形式 抓包&#xff0c;将png改为php 然后放包上传成功 2.提示说检查数据类型 抓包 将数据类型改成 image/jpeg 上传成功 3.提示 可以用phtml&#xff0c;php5&#xff0c;php3 4.先上传.htaccess文件&#xff0…

金融支付行业技术侧重点

1. 合规问题 第三方支付系统的平稳运营&#xff0c;严格遵循《非银行支付机构监督管理条例》的各项条款是基础与前提&#xff0c;其中第十八条的规定堪称重中之重&#xff0c;是支付机构必须牢牢把握的关键准则。 第十八条明确指出&#xff0c;非银行支付机构需构建起必要且独…