Qian Kun Practical Tutorial

1. What is a micro-frontend architecture

Micro-frontend is not a simple front-end framework or tool, but a set of architecture system. This concept was first proposed at the end of 2016. You can refer to the top-ranked http://micro-frontends.org on Google to search for Micro-Frontends. Blog post proposing an early micro-frontend model.

Qianshort is an architecture similar to microservices, which applies the concept of microservices to the browser side, that is, transforms a single-page front-end application from a single application to a single application that aggregates multiple small front-end applications. Each front-end application can also be developed and deployed independently.

The micro frontend architecture is designed to solve monolithic applications over a relatively long time span due to the people involved. The increase and change of the team, from an ordinary application to a superstar application, followed by the problem of unmaintainable applications. This type of problem is especially common in enterprise web applications.

The realization of the micro-frontend means the splitting of the front-end application. The purpose of splitting the application is not just to look good in structure, it can also improve development efficiency. For example, if 100,000 lines of code are split into 10 projects, and each project has 10,000 lines of code, it will be much easier to maintain each project independently. And we only need to achieve the autonomy of the application, and realize the independent operation and deployment of the application, which can be achieved to some extent as the purpose of the front-end architecture.

2. Usage scenarios

Micro-frontends help developers solve practical problems, but for each business, whether it is suitable for use as a frontend, and whether it is used correctly, the following principles still need to be followed:

  1. The best usage scenarios for micro-frontends are some B-segment management systems, which can be compatible with existing systems and integrate new systems without affecting the original interaction system.
  2. The overall micro-frontend is not just the integration of the system, but the improvement of the entire micro-frontend system, which includes:
    • Auto-deployment capabilities for base applications and micro-applications
    • Micro-application configuration management capabilities
    • Local development and debugging capabilities
    • Online monitoring and statistical capabilities, etc.

Only when the entire capability system is fully established can it be said that the entire micro front-end system process is complete.

In addition, he also has a series of shortcomings:

  • The separation of basic dependencies and infrastructure construction of applications, once a large number of applications rely on a unified infrastructure, then maintenance becomes a challenge.
  • The smaller the split, the more complex the structure and the higher the maintenance cost
  • Once the technology stack is diversified, it means that the technology stack is chaotic

When it is found that using the front-end will reduce the efficiency, and the simple change is complicated, it means that the front-end is not applicable.

3. How to implement the micro front end

In terms of technical practice, the following methods can be used for the front-end architecture:

  1. Routing distribution. The request is routed to the corresponding application through the reverse proxy function of the http server.
  2. Front-end micro-serverization, designing communication and loading mechanisms on top of different frameworks to load corresponding applications in one page.
  3. micro app. Through software engineering, multiple independent applications are combined into a single application in the deployment and construction environment.
  4. Widgetization. Develop a new build system to build some business functions into an independent chunk code, which only needs to be loaded remotely when used.
  5. Front-end containerization. Will act iframeas a container to hold other front-end applications.
  6. Application componentization. With the help of Web componentstechnology, to build cross-framework front-end applications.

Although there are many ways to implement, they are all adopted according to the scene. In some scenarios, there may be no suitable method; in some scenarios, multiple methods can be used at the same time.

4. Architecture mode

Centralization: Pedestal Mode

In the front-end architecture of this model, the base bears the foundation and technical core of the micro-front-end application. The base mode is a system composed of a main application and a series of business self-applications, and the main application manages other sub-applications, including life cycle management of sub-applications and communication mechanisms between applications.

The main application in the pedestal mode is similar to API Gatewaythe concept of . As the unified entrance of the system, it is responsible for directing the corresponding request to the corresponding service. The sub-application is responsible for the business implementation of each sub-module, and its architecture is shown in the figure.

insert image description here

This main application can either have a simple base function or a business function. The business functions it deals with refer to the core business functions, such as:

● User login and registration management.
● Unified authentication management of the system.
● Navigation menu management.
● Routing management.
● Data management.
● Communication agent.
●...

As the base core of the application, it also requires:

● Maintain application registry. Indicate on the application registry how many services the system has, whether the corresponding application can be found, and so on.
● Manage other sub-applications. Such as when to load the application, when to unload the application, etc.

To realize the micro-frontend architecture of this model, it is only necessary to design the corresponding application loading mechanism, so it is more convenient to implement.

A typical representative of the centralized micro-frontend architecture is: Qiankun

Decentralization: self-organizing model

The decentralized self-organization model refers to the fact that the subsystems within the system can form a certain structure or function according to certain rules. By adopting this mode, various front-end applications in the system can each have a small base management function, which means that each application can be a base.

When using the dock mode, if the user wants to access the A application, the main application needs to be loaded first, and then the A application can be loaded. When the self-organizing mode is adopted, the user only needs to access the A application if he wants to access the A application, and does not need to load the main application, which makes it have higher autonomy.

But most of the time, we don't need the self-organizing micro-frontend architecture, because it is complex in design and has a lot of repetitive code.

There is a good implementation of decentralized micro-frontend design, which is the module federation of basic webpack that will appear in 2020.

5. Micro front-end architecture solution

Single-Spa : The earliest micro front-end framework (2018), compatible with multiple front-end technology stacks, the core is only for routing hijacking and application loading.
○ It does not handle style isolation and JavaScript execution isolation
Qiankun : Born in 2019, based on Single-Spa, Ali is an open source micro-frontend framework. The support for vite is not very good
○ single-spa + sandbox + import-html-entry
○ It solves style isolation and JavaScript execution isolation
○ Simple access
● 2020 webpack5 module federation
● 2020 EMP based on Module Federation (module federation), Low access cost, solving the problem of third-party dependent packages
Icestark : Alibaba Feibing micro front-end framework, compatible with multiple front-end technology stacks.

Six, qiankun quick start

Introduction to qiankun

● qiankun is a micro-frontend implementation library based on single-spa, designed to help you build a production-ready micro-frontend architecture system more easily and painlessly.
● Easy to use
○ Technology stack-independent, applications of any technology stack can be used/accessed, whether it is React/Vue/Angular/JQuery or other frameworks.
○ The HTML Entry access method allows you to access micro-apps as easily as using an iframe.
● Complete functions: It contains almost all the basic capabilities needed to build a micro front-end system.
○ Style isolation ensures that styles between micro-apps do not interfere with each other.
○ JS sandbox to ensure that global variables/events do not conflict between micro-apps.
○ Resource preloading, preloading unopened micro-app resources during browser idle time, speeding up the opening of micro-apps.
○ The umi plugin provides @umijs/plugin-qiankun for one-click switching of umi applications to micro-frontend architecture systems.
● Available for production: qiankun was hatched from Ant Financial Technology’s unified access platform for cloud products based on the micro-frontend architecture. To help the community with similar needs to build their own micro-frontend systems more conveniently, and also hope that through the help of the community, qiankun will be polished to a more mature and perfect state. At present, qiankun has served more than 200+ online applications within Ant, and is absolutely trustworthy in terms of ease of use and completeness.
● Architectural idea: a typical representative of the micro-frontend of the centralized pedestal model, a system composed of a main application and a series of business sub-applications, and the main application manages other sub-applications, including life cycle management of sub-applications to application communication mechanism between them.

main application

1. Create a project

First install the vue-vli command line tool:npm install -g @vue/cli

Create main、app1、app2three projects:

  • vue create main(Choose vue3 with router version)
  • Then copy the main code to app1,app2

2. Main project configuration (main)

In the main project, add a div container.

app.view:

<template>
  <div id="app">
    <div id="nav">
      <router-link to="/">Home</router-link> |
      <router-link to="/app1">app1</router-link> |
      <router-link to="/app2">app2</router-link>
    </div>
    <router-view/>
    <div id="container"></div> <!--子应用容器-->
  </div>
</template>

Register sub-applications:

main.ts:

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import {
    
     registerMicroApps,setDefaultMountApp , start } from "qiankun";

Vue.config.productionTip = false

new Vue({
    
    
  router,
  store,
  render: h => h(App)
}).$mount('#app')

registerMicroApps([
  {
    
    
    name: 'app1',
    entry: '//localhost:8082',
    container: '#container',
    activeRule: '/app1',
  },
  {
    
    
    name: 'app2',
    entry: '//localhost:8083',
    container: '#container',
    activeRule: '/app2',
  },
]);

setDefaultMountApp("app1")
// 启动 qiankun
start();

3. Subproject configuration (app1)

a. Create-src/public-path.js

if (window.__POWERED_BY_QIANKUN__) {
    
    
    __webpack_public_path__ = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__;
}

b. Modify-main.js

import './public-path';
import Vue from 'vue';
import VueRouter from 'vue-router';
import App from './App.vue';
import routes from './router';
import store from './store';

Vue.config.productionTip = false;

let router = null;
let instance = null;
function render(props = {
     
     }) {
    
    
  const {
    
     container } = props;
  router = new VueRouter({
    
    
    base: window.__POWERED_BY_QIANKUN__ ? '/app1/' : '/',
    mode: 'history',
    routes,
  });

  instance = new Vue({
    
    
    router,
    store,
    render: (h) => h(App),
  }).$mount(container ? container.querySelector('#app') : '#app');
}

// 独立运行时
if (!window.__POWERED_BY_QIANKUN__) {
    
    
  render();
}

export async function bootstrap() {
    
    
  console.log('[app1] vue app bootstraped');
}
export async function mount(props) {
    
    
  console.log('[app1] props from main framework', props);
  render(props);
}
export async function unmount() {
    
    
  console.log('[app1] unmount');
  instance.$destroy();
  instance.$el.innerHTML = '';
  instance = null;
  router = null;
}

/**
 * 可选生命周期钩子,仅使用 loadMicroApp 方式加载微应用时生效
 */
 export async function update(props) {
    
    
  console.log('update props', props);
}

c. Packaging configuration - vue.config.js

const {
    
     name } = require('./package');
module.exports = {
    
    
  devServer: {
    
    
    headers: {
    
    
      'Access-Control-Allow-Origin': '*',//支持跨域
    },
    port:8082
  },
  configureWebpack: {
    
    
    output: {
    
    
      library: `${
      
      name}-[name]`,
      libraryTarget: 'umd', // 把微应用打包成 umd 库格式
      jsonpFunction: `webpackJsonp_${
      
      name}`,
    },
  },
};

app2 is configured like app1. Note that the startup port is configured as: 8083.

4. Start

Start the main, app1, and app2 projects respectively; then open the main application address.

Please add a picture description

5. Deployment

Main app and micro app are deployed to the same server (same IP and port)

a. Main application-main.js

registerMicroApps([
  {
    
    
    name: 'app1',
    entry: '/child/app1',
    container: '#container',
    activeRule: '/app1',
  },
  {
    
    
    name: 'app2',
    entry: '/child/app2',
    container: '#container',
    activeRule: '/app2',
  },
]);

b. Sub-application publicPath+base

view.config.js

const {
    
     name } = require('./package');
module.exports = {
    
    
  devServer: {
    
    
    headers: {
    
    
      'Access-Control-Allow-Origin': '*',
    },
    port:8082
  },
  publicPath:"/child/app1/", // 主要调整的这里
  configureWebpack: {
    
    
    output: {
    
    
      library: `${
      
      name}-[name]`,
      libraryTarget: 'umd',
      jsonpFunction: `webpackJsonp_${
      
      name}`,
    },
  },
};

router/index.js

const router = new VueRouter({
    
    
  mode: 'history',
  base: window.__POWERED_BY_QIANKUN__ ? '/app1/' : '/child/app1/',
  routes
})

app2 is also configured.

Main, app1, and app2 execute npm run build packaging; copy the dist directory generated by packaging app1 and app2 to main/dist/child, and rename it to app1 and app2. The adjusted directory structure is shown in the figure:

insert image description here
Create an http service locally, http-server distand then you can access it normally;

Also need to fix http://127.0.0.1:8081/app1the 404 on refresh.

source code

Guess you like

Origin blog.csdn.net/bobo789456123/article/details/126696493