What is a micro front end

The qiankun was hatched from Ant Fintech’s unified access platform for cloud products based on micro-front-end architecture. It is a single-SPa-based micro-front-end implementation library, aiming to help people build a production-usable micro-front-end architecture system more easily and painlessly. The micro front end is a kind of technical means and method strategy that multiple teams jointly build modern Web applications by releasing functions independently.

What are the advantages?

The micro front-end architecture has the following core values:

  • Stack independent
    • The main framework does not limit access to the technology stack, and microapplications have full autonomy
  • Independent development and deployment
    • The microapplication repository is independent, and the front and back ends can be developed independently. After the deployment, the main framework can be updated synchronously
  • The incremental upgrade
    • In the face of a variety of complex scenarios, it is usually difficult to upgrade or reconstruct the existing system completely, and the micro front end is a very good means and strategy to implement the gradual reconstruction
  • Independent run time
    • State is isolated between each microapplication and run time state is not shared

Let’s implement a small example first.

New project

Install @ vue/cli

npm install -g @vue/cli
Copy the code

Initialize the project

Vue Create projectName - Creating a project slowly? The old NPM cache conflicts with the project (the NPM version is too low, just upgrade NPM to the latest version, upgrade: NPM install -g NPM). Step 1: > NPM cache clean --force 2. Step 2 > NPM config set registry at https://registry.npm.taobao.orgCopy the code

Install @vue/typescript dependencies

Open the project, execute vue add@vue /typescript on the console, always Yes. @ @ ~ ~ ~Copy the code

Create the main body

The installation depends on NPM install Qiankun-sCopy the code

The main project configuration is very simple, just look at the API documentation.

// For the simplest configuration, add the following code to main.js
import { registerMicroApps, start } from 'qiankun'
const apps = [
  {
    name: 'zht_base-app'.// Application name
    entry: '//localhost:9090'.// Application entry, resource path
    container: '#vue'.// The container id that holds the child application in the body
    activeRule: '/vue'.// Switch the subapplication according to the rule to activate the rule
    props: {
      // The data passed to the child application
      name: 'zht_base-app'.entry: '//localhost:9090'
    }
  }
]

registerMicroApps(apps, {
  beforeLoad: (app) = > {
    console.log('Print apps before loading the app', app)
  }
})

start({
  // Whether to enable preloading. Default value: true.
  // Set to true to preload static resources for other microapplications after the first microapplication mounts
  prefetch: false.// boolean | { strictStyleIsolation? : boolean, experimentalStyleIsolation? : boolean
  sandbox: true
})
Copy the code

Principal Route Configuration

Note: The layouts are in the
file in app. vue, and the main content area is in the router-view. The render container (#subAppContainer) is also located in the layouts, and the activation route (/ vUE) is configured in the layouts. Otherwise, when switching to the microapp, an error will be reported stating that the container for the microapp is not found. So if you want to render a microapp in loyouts’ #subAppContainer, configure the activation rule in the routing table. The component layout of the route is layouts, and when you click the /vue menu, The microapplication can correctly find the container at the time of registration.

The actual application scenario is generally not like this. The menu part is the menu of each application. Different applications are rendered by switching between applications through a drop-down menu (or other forms), and the menu is dynamically rendered by the dynamic addRoutes function of vue-Router.

import Vue from 'vue'
import VueRouter from 'vue-router'
// typescript only recognizes *. Ts files by default and does not recognize *. Vue files, so import
import LoginPage from '@/views/login/index.vue'
import HomePage from '@/views/home/index.vue'
import Layouts from '@/layouts/index.vue'

Vue.use(VueRouter)

const router = new VueRouter({
  mode: 'history'.routes: [{path: '/'.component: Layouts,
      children: [{path: '/login'.component: LoginPage
        },
        {
          path: '/home'.component: HomePage
        }
      ]
    },
    {
      path: '/vue'.component: Layouts,
      children: [{path: 'about'
        },
        {
          path: 'home'}]}]})export default router
Copy the code
  • The main structure

    • Apply colours to a drawing area

    • Part of the menu

    subAppLists = [
      {
        name: 'vue app'.homePath: '/vue'
      },
      {
        name: 'login'.homePath: '/login'
      },
      {
        name: 'home'.homePath: '/home'}]Copy the code

Configuring microapplications

Sub-application Configuration

The sub-application can be configured and connected to the main application without downloading any plug-insCopy the code

The child application exports the hook function

Child applications must export hook functions required by the body.

export async function bootstrap(params: object) {
  console.log('subapp bootstraped')}/** * The application calls the mount method every time it enters, and usually we trigger the application's render method here */
export async function mount(params: object) {
  console.log('subapp parent data', params)
  render()
}

/** * The method that is called each time the application is cut/unloaded, usually here we unload the application instance of the microapplication */
export async function unmount(props: object) {
  console.log('subapp destroyed')
  instance.$destroy()
  instance = null
}
Copy the code

Child applications that run through WebPack also need to be configured with WebPack

1.
// In order for the main application to correctly identify some of the information exposed by the micro-application, the micro-application packaging tool needs to add the following configuration
const packageName = require('./package.json').name;
module.exports = {
  output: {
    library: `${packageName}-[name]`.libraryTarget: 'umd'.jsonpFunction: `webpackJsonp_${packageName}`}}2.
/ / publicPath configuration
// The qiankun will inject a runtime publicPath variable before the microapplication bootstrap. All you need to do is add the following code to the microapplication entry file (usually main.js) :
__INJECTED_PUBLIC_PATH_BY_QIANKUN__ represents the running resource path of the project, such as http://localhost:9090/
__webpack_public_path__ = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__
Copy the code

How does a subapplication run an application independently

function render() {
  instance = new Vue({
    router,
    render: h= > h(App),
  }).$mount('#vue-app')}if (!window.__POWERED_BY_QIANKUN__) {
  // If the child is running independently, render directly
  render()
} else {
  // Otherwise, the child application is called in the body
  __webpack_public_path__ = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__
}

export async function mount(params: object) {
  render()
}
Copy the code

rendering

Demo renderings, click the Vue APP menu, you can switch to the micro application. Login and home menus are the center menus themselves and are rendered in gray.

Through this, we learned how to build our own micro front-end service through Qiankun. I will continue to update the document later to see how we can create enterprise-class middle and background applications through Qiankun!!

At the end

Keep updating. If you enjoyed this section, make sure you don’t get lost.

To communicate with

Join our QQ group and exchange technology with you