**Micro Frontend Framework Development Notes**
---
### **1. Architectural Thinking**
#### **1.1 Software Design Principles**
- **Single Responsibility Principle (SRP)**: A class should not be responsible for more than one reason.
- **Open-Closed Principle (OCP)**: A system should be open for extension but closed for modification.
- **Liskov Substitution Principle (LSP)**: A subclass should be able to replace its parent class without breaking functionality.
- **Dependency Inversion Principle (DIP)**: High-level modules should not depend on low-level modules; they should depend on abstractions. Abstractions should not depend on details; details should depend on abstractions.
- **Interface Segregation Principle (ISP)**: Classes should not be forced to depend on interfaces they don't use.
**Implementation**: Following these principles ensures stable and maintainable software architecture.
#### **1.2 Architectural Types**
- **System-Level Architecture**: Micro frontend is a system-level architecture.
- **Application-Level Architecture**: Includes scaffolding, UI libraries, and design systems.
- **Module-Level Architecture**: Iterative development.
- **Code-Level Architecture**: Code standards and design principles.
**Key Insight**: Micro frontend is a system-level architecture, but it can also be considered an inter-system architecture between multiple applications.
#### **1.3 Micro Frontend Implementation Methods**
- **Single Instance**: One sub-app is displayed at a time, with full lifecycle management.
- **Multi-Instance**: Multiple sub-apps can be displayed simultaneously, with switching based on URL changes. Uses Web Components for encapsulation, making sub-apps more business-oriented than full applications.
**Stability**: A system is stable if it returns to its original state after external interference. Otherwise, it's unstable.
**Key Benefits**:
- **Fault Tolerance**: Systems can self-heal.
- **Robustness**: Software should handle errors, disk failures, network overload, and intentional attacks.
**Metrics for Robustness**:
1. Input validation to derive correct outputs from incorrect inputs.
2. Stability across different environments.
3. Detection and handling of internal design/implementation errors.
#### **1.4 Conceptual Measures for Architecture Quality**
- **Extensibility**
- **Maintainability**
- **Manageability**
- **High Availability (Fault Tolerance)**: Includes fault recovery, disaster recovery, degradation, and circuit breaker mechanisms.
#### **1.5 Architecture Quality in Daily Development**
- **Ease of Understanding**
- **Dependency Cost of Integration**
- **Crash Rate and Error Rate**
- **Development Efficiency**
- **Error Reporting and Information Collection**
#### **1.6 Pre-Architecture Preparation**
- **Architectural Categories**:
- **System Architect**: Focuses on overall system architecture, pure technical design.
- **Application Architect**: Focuses on business systems, emphasizes understanding business logic.
- **Business Architect**: Focuses on industry-specific processes, may diverge from code development, emphasizing data analysis.
#### **1.7 Origin of Technical Debt**
- **Time Pressure**: Inefficient implementations due to rushed development.
- **Suboptimal Solutions**: Compromising on better alternatives.
- **Omitted Details**: Issues overlooked during initial architecture design.
- **Complexity from Poor Interaction Design**.
- **Lack of Documentation**: Old features without proper documentation or expansion interfaces, leading to difficulty in deployment.
**Consequences of Accumulated Technical Debt**:
- **Inefficient Refactoring**:严重影响 productivity.
- **Compatibility Issues**: Constant need to adjust legacy functionality, slowing development.
#### **1.8 Technical Gap Filling**
- **Code Decoupling**: Module splitting and code isolation.
- **Logging**: Operational logs, error logs, and business logs.
- **Training and Mentorship**: Technical training and knowledge transfer.
- **Code Standards**: Writing clear code documentation.
- **Code Reviews**: Engineers reviewing each other's code.
- **Technical Debt Detection**: Tools to identify and track technical debt.
**Post-Release**: After product release, development no longer feels urgent. Use this time to address technical debt, build relationships, and appreciate original code.
#### **1.9 Preventing System Crashes**
- **System Crash as a Critical Design Error**.
- **Crash Prevention**:
- **User Behavior Analysis**: Track user interaction paths.
- **Resolve Existing Technical Debt**.
- **Reduce New Issues**.
- **兜底 and Validate Dirty Data**.
- **Unit Testing**.
- **Crash Warning**.
- **Automated Testing**.
- **Wider Gray Release Coverage**.
- **Performance Optimization Framework**.
**When Technical Debt Accumulates**: Small projects can consider full refactoring. For complex systems, micro frontend architecture becomes a solution for architectural optimization (micro refactoring).
#### **1.10 Refactoring Process**
- **Identify Issues and Define Refactoring Scope**.
- **Review and Analyze Existing Architecture**.
- **Ensure Stability**.
- **Ensure Performance**.
- **Handle Conflicts in Requirements**
---
### **2. Initial Understanding of Micro Frontend**
#### **2.1 Micro Frontend Implementation Methods**
- **Iframe**: Mature technology, supports page embedding, sandbox isolation, and independent operation.
- **Pros**: Mature, easy to use.
- **Cons**: Different domain names, need to design communication mechanisms, browser handles rendering and caching, low control.
- **Web Component**: Supports custom elements, shadow DOM, and template slots.
- **Pros**: Customizable, supports template and slot.
- **Cons**: Requires rewriting the entire project, ecosystem incomplete, compatibility issues, complex architecture, difficult component communication.
- **Self-Designed Framework**: High customization, supports all compatibility scenarios; independent communication mechanism and sandbox environment, solves mutual interference between applications; supports different tech stacks, seamless page rendering without refresh.
- **Cons**: High implementation difficulty; need to design a custom communication mechanism; large resource consumption during initial load.
**Final Decision**: Choose self-designed framework.
- **Routing Distribution**:
- **Main Application Controls Routing and Sub-App Loading, Sharing Dependencies**.
- **Sub-Apps Implement Features and Integrate with Main Application for Bidirectional Control**
#### **2.2 Determining Technology Stack**
- **Main Application**: Vue3.
- **Sub-Apps**:
- **Vue2**: New energy application.
- **Vue3**: Home page, car selection.
- **React15**: News, video, video details.
- **React16**: New car, ranking, login.
- **Backend Services and Publishing Application**:
- **Service**: Koa.
- **Publish Application**: Express.
- **Implementing Micro Frontend Framework**: Handwritten using native Node.js.
#### **2.3 Analyzing the Framework**
- **Main Application**:
1. Register sub-apps.
2. Load and render sub-apps.
3. Route matching (activeWhen, rules by framework).
4. Data retrieval (public data, with authorization checks).
5. Communication mechanism (parent-child communication, both directions).
- **Sub-App**:
1. Render own functionality.
2. Listen for communication (data passed by main application, update accordingly).
- **Micro Frontend Framework**:
1. Register sub-apps.
2. Start content (application loaded, micro frontend framework starts).
3. Match corresponding sub-app, load its content, execute all dependencies.
4. Render sub-app in a fixed container.
5. Public event management.
6. Exception capture and reporting.
7. Global state management.
8. Sandbox isolation, ensuring sub-apps are not interfered with by other sub-apps.
9. Communication mechanism.
- **Server-side Functions**:
1. Provide data services.
2. Main and sub-app packaging and publishing.
#### **2.4 Organizing Thoughts and Drawing Project Architecture Diagram**
- **Tools Recommended**: Processon.
**Image**: [Image Caption: "image.png"].
#### **2.5 Auto-Startup Script for All Sub-Apps**
- **In root directory's package.json**: Configure start command.
- **Content**: Configure a script to run an instruction and open all applications simultaneously.
#### **2.6 Building the Service**
- **Build a Backend Service**:
- `npm install koa-generator -g`
- `koa -V`
- `koa2 service`
- **Quickly Generate a Koa2 Project**:
- `bin/www` is the startup file.
- `public` is the static resource directory.
- **Install a Plugin for Automatic Restart**:
- `npm install supervisor --save-dev`
- Use `supervisor` instead of `node` in the start command.
**Cross-Origin Solution with Koa**:
- `npm install koa2-cors --save-dev`
- `const cors = require('koa2-cors')`
- Set the service to cross-origin mode.
**Request Handling**:
- `ctx.request.query` retrieves parameters from the frontend interface path.
- `ctx.request.body` for POST requests.
#### **2.7 Sub-App Integration with Micro Frontend Vue2**
- **Steps**:
1. Main application gains sub-app lifecycle, structure, methods, and files.
2. Vue2 sub-app integrates with micro frontend.
- **Vue2 Sub-App Integration**:
- Configure `vue.config.js` with `devServer.contentBase` and `headers` to allow cross-origin and output.
- **Vue2 Sub-App**:
- Create an instance of `new Vue()` in the micro frontend framework.
- The execution and destruction of this instance should be handled by the main application.
- **Files to Modify**:
- `vue.config.js`
- `main.js`
#### **2.8 Main Application Development**
- **Central Controller - Main Application**:
- Uses Vue3 technology stack.
- **Main Application**:
- Sets up a container for sub-apps on the page.
- **Sub-App Registration**:
- In the main application, register sub-apps.
- `leftNav.js` in the `store` file records sub-app registration information.
- `startMicroApp.js` in the `utils` folder provides a method to start micro apps.
- **Route Interception**:
- Listen for route changes, rewrite route events, and remember browser's back/forward buttons (`window.onpopstate`).
- **Micro Frontend Framework**:
- Get the first sub-app.
- When entering the project, the first displayed sub-app is validated. If the list is empty, it matches the current route to find the corresponding sub-app. If the sub-app exists, it redirects to the sub-app's URL.
- **Avoid Multiple Custom Route Events**: Add a marker to the window object to prevent multiple triggers.
- **Code**:
```javascript
window.__CURRENT_SUB_APP__ = app.activeRule;
if (window.__CURRENT_SUB_APP__ === window.location.pathname) {
return;
}
```
**Control Sub-App Content with Main Application Lifecycle**:
- **beforeLoad**: Begin loading.
- **mounted**: Render complete.
- **destoryed**: Unload complete.
- **Main Application Lifecycle Events**: Saved in the micro frontend, controlled by the global loading state.
**Micro Frontend Mounting**:
- When the main application registers, it passes the main application's lifecycle to the micro frontend framework. The framework iterates through all lifecycle events of the main application, generating registration in the main application.
- **Micro Frontend Lifecycle**:
- When the route changes, the framework performs corresponding destruction and loading operations on the sub-app.
**Fetching Pages to Display**:
- **Loading and Parsing HTML**:
- In the main application's `beforeLoad` lifecycle, fetch page content.
- Sub-app page display is achieved via GET requests (network documentation), allowing the micro frontend framework to fetch the sub-app's page via GET, retrieve `res`, and then `res.text()` to get the page content, assigning it to the corresponding container to display the sub-app's page. However, directly assigning to the container prevents it from parsing HTML tags like `` and `