preface

Before we dive into the micro front end, let’s get to know some concepts about microservices. Here’s an excerpt from Wikipedia:

Microservices are a style of software architecture that modular large complex applications based on Small Building Blocks that focus on a single responsibility and function. Functional blocks communicate with each other using a language-independent /Language agnostic SET of apis.

Introduction to the micro front end, because there is no official definition of the micro front end, the following introduction comes from the community:

Microfront-end is a kind of architecture similar to microservices. It applies the concept of microservices to the browser side, that is, the Web application is transformed from a single single application into a combination of several small front-end applications. Each front-end application can run, develop and deploy independently.

This article is a summary of work practices, and I hope you can learn the following after reading this article:

  • Have a simple understanding of micro front-end, want to achieve a demo.
  • Try to complete a practice in the context of your project.

The body of the

Introduction to the micro front End

Here’s how to explain the micro front end using the 3W principle:

  1. What is a micro front end?
  2. Why use a micro front end?
  3. How to get to the landing micro front end?

What is a micro front end?

First above:

(Photo from Internet)

Let’s say we now have a super app that has been iterating for years, with modules like the home page, category page, shopping cart page, order page, and so on. If we have a new requirement for a function in a module, we need to launch the whole application and update the whole project, which is a headache. Incremental updates can be achieved if we split the large application into modules and independently publish and deploy the subprojects after the split. So with that example, let’s move on, what is a micro front end?

Since there is no specific definition of a microfront end, the following introductions come from the community:

  • It is a microservices-like architecture.
  • It applies the concept of microservices to the browser side, that is, the Web application from a large single application into a number of small front-end applications into one application.
  • Each sub-application can be independently developed, run and deployed.
  • The core of the micro front end is disassembly, disassembly and reassembly.

Why use a micro front end?

Why to use it, we have to first see where our pain points are, whether it can help us solve these pain points.

First, let’s look at the pain points we might encounter:

  • What if different teams develop the same application with different technology stacks?
  • What if you want each application module to be independently developed and deployed?
  • .

After looking at the pain points we may face, let’s look at the advantages of the micro front end:

  • The split code is cleaner, decoupled, and more maintainable.
  • As with microservices, a big advantage of the microfront end is the ability to be independently deployable.
  • Partial/incremental upgrade
  • Organizations are more scalable, and their teams are more autonomous.
  • Can keep pace with The Times, constantly introducing new technologies/frameworks, not limited by technology.
  • .

After looking at its advantages, the use of micro front-end in the right scenario can bring us great benefits!

How do I get to the landing micro front end?

Before we get to the ground micro front, let’s talk a little bit about the history of the micro front,

The concept of a micro front end was first proposed by ThoughtWorks in 2016, and has since been quickly adopted by the industry and adopted by major Internet companies.

In 2018, Single-SPA was born. Single-spa is a javascript front-end solution for front-end microservitization (no style isolation, JS execution isolation itself) that implements route hijacking and application loading.

A more out-of-the-box API based on Single-SPA (Single-SPA + Sandbox + import-HTmL-Entry) that is stack independent and easy to access (how easy is it, as simple as iframe)

At present, there are several common ways to realize the micro front end:

  1. Route distribution: The reverse proxy function of the HTTP server forwards the request route to the application.
  2. Front-end microservitization: Design communication and loading mechanisms on top of different frameworks, and finally load corresponding applications in a single page.
  3. Microapplication: To combine multiple independent applications into a single application in a deployment build environment through software engineering.
  4. Microcomponentization: Develop a new build system that builds parts of the business into a separate chunk of code that can be loaded remotely.
  5. Front-end containerization: Use iframe as a container to introduce other front-end applications.
  6. Application components: with the help of Web Components technology, to build the front-end application of the framework.

The micro front end involves:

First above:

(Photo from Internet)

As shown in the figure above, there is a huge knowledge system involved behind the micro front end, such as how to provide an independent runtime environment of JS for each sub-application, prevent CSS coverage between sub-applications, trigger of sub-application registration, mount and unmount, etc

QMS practice

Problems faced

The original project of QMS quality system has some problems, such as adopting Angular to develop the front-end part, requiring special personnel to maintain, long time line for newcomers to learn, high development cost, and inability to further develop technical compliance. In order to help the QMS team solve the problems they are facing, after internal discussion of the team, the react+ HIUI development of new requirements is adopted on the basis of the original project, and the micro front end is adopted for integration.

Implementation and architecture diagram

In the QMS system, the project is implemented in the following ways:

As shown in the figure above, the project is divided into the central base application and one or more sub-applications. The base application stores the registration information of all sub-applications. Through logical processing in the main project, the application is initialized. Single-spa realizes route hijacking by listening for URL changes, connects the application loader to the sub-application, and mounts and unmounts the sub-application through the life cycle exposed by the sub-application.

QMS Architecture Diagram:

The following is a detailed demo code:

Center of the base

1. Application loader

import * as singleSpa from 'single-spa' import config from './manifest.prod.json' registerApp(config) singleSpa.start() Function registerApp(conf) {console.log('-- registerApp --', conf) conf.forEach((application) => { singleSpa.registerApplication( application.name, () => window.System.import(application.name), pathPrefix(application.activeRule, application.strict), ) }) } function pathPrefix(prefix, strict = false) { return function (location) { if (strict) { return location.pathname === prefix } return location.pathname.startsWith(`${prefix}`) } }Copy the code

2. Application registry table, which contains the registration information of all sub-applications of the project, such as packaged JS files and route prefixes (used for mounting and unmounting logic).

[{
    "name": "layout-app",
    "activeRule": "/",
    "strict": false,
    "url": "http://localhost:3006/js/main-layout.js"
  },
  {
    "name": "react-app",
    "activeRule": "/v2",
    "strict": false,
    "url": "http://localhost:3007/js/main-v2.js"
  },
  {
    "name": "angular-app",
    "activeRule": "/v1",
    "strict": false,
    "url": "http://localhost:3008/js/main-v1.js"
  }
]

Copy the code

3. System.js introduction and configuration

Systemjs is a minimal system loading tool that creates plug-ins to handle alternative scene loading processes, including loading CSS scenes and images, primarily in browsers and Node.js. It is an extension to the ES6 browser loader and will be used in local browsers. The name of the plug-in that is usually created is the module itself, and if the purpose is not specified, the default plug-in name is the extension name of the module.

As a module loader, system.js provides a common module import path, supporting traditional modules and ES6 modules. We need system.js to do this for us:

  • Register and load the module files of the sub-application
  • Register and load the common library

Add system.js to the HTML template file:

<script type="systemjs-importmap"> <%= htmlWebpackPlugin.options.importmap %> </script> <! -- < script SRC = "https://cdn.jsdelivr.net/npm/[email protected]/dist/zone.min.js" > < / script > -- > < script src="https://hd.mi.com/f/zt/hd/20200805/systemjs/system.min.js"></script> <script src="https://hd.mi.com/f/zt/hd/20200805/systemjs/amd.min.js"></script> <script src="https://hd.mi.com/f/zt/hd/20200805/systemjs/named-exports.js"></script> <script src="https://hd.mi.com/f/zt/hd/20200805/systemjs/use-default.min.js"></script>Copy the code

The child application

In each sub-application, three life cycles (bootstrap, mount, and unmount) and corresponding mounted nodes need to be exposed.

1. Mount information of subapplications

import React from 'react' import ReactDOM from 'react-dom' import singleSpaReact from 'single-spa-react' import App from  './App' const reactLifecycles = singleSpaReact({ React, ReactDOM, rootComponent: App, domElementGetter, }) export function bootstrap(props) { return reactLifecycles.bootstrap(props) } export function mount(props) { return reactLifecycles.mount(props) } export function unmount(props) { return reactLifecycles.unmount(props) } function domElementGetter() { // Make sure there is a div for us to render into let el = document.getElementById('react-app') if (! el) { el = document.createElement('div') el.id = 'react-app' document.getElementById('sand-box').appendChild(el) } return el }Copy the code

2. Isolate sub-applications using CSS

In order to prevent CSS style overwriting between applications, it is necessary to achieve style isolation between sub-applications. Common CSS specifications are:

  • Bem specification: It is a convention specification and requires the developer to actively follow the specification
  • Css-modules: Add hash values when packing to generate unique class names
  • Shadow DOM: True isolation
  • Third-party plug-ins: PostCSS plug-ins are used in the project to add prefixes to sub-application CSS

The React sub-application is used as an example:

module.exports = {
  plugins: [
    require('autoprefixer'),
    require('postcss-flexbugs-fixes'),
    require('postcss-preset-env')({
      autoprefixer: {
        flexbox: 'no-2009',
      },
      stage: 3,
    }),
    require('postcss-plugin-namespace')('#react-app'),
  ],
}

Copy the code

The above is the core part of the display, the implementation of sub-application registration, mount, uninstall, application style isolation.

harvest

The QMS micro front end integration realizes that the original page retains Angular, new functions are developed using React + HIUI, and the subsequent development is unrelated to the technology stack. CLI build speed increased by 50% by adjusting webPack configuration (average build time reduced from 16min to 8min). For those interested in improving build speed, read this article about how to optimize Angular projects by eliminating cascading modules. It details how to optimize Angular project packaging during micro-front-end integration.

Summary & afterword

Summary of advantages and disadvantages of micro front-end

Advantages of the micro front-end:

  • Sub-applications can be developed and deployed independently.
  • It can not be limited by technology, while maintaining the original system, it can also introduce new technology to improve development efficiency and user experience.
  • Partial/incremental upgrades can be implemented for sub-applications when requirements change, rather than upgrading the entire project.
  • The code is more concise, easy to maintain, and the coupling degree is reduced.

The significance and impact of the micro front end is unprecedented, and more and more teams are beginning to think and use the micro front end architecture.

Disadvantages of the micro front end

While the micro front end brings us advantages, it also has some disadvantages:

  • Duplicate dependencies: When subapplications rely on duplicate packages, this situation is inevitable because the applications are distributed and deployed independently.
  • More fragmented teams: The fragmentation of systems, with each team only responsible for its own business function delivery, can lead to less sensitivity to the user experience.

Not all projects are suitable for the introduction of a micro front end, so use the micro front end appropriately according to your business scenario to maximize revenue and reduce unnecessary investment.

Summary of landing scenarios for micro-front-end applications

  • Compatibility with legacy systems: If your original project doesn’t match your current team’s stack, or if the framework is too far behind, it’s a good idea to use a micro front end to blend the fineness of the stack.
  • Application aggregation: The micro front end is a good choice for the splitting and aggregation of super-large projects, which is similar to the mid-stage system in the company, hoping to provide more convenient and efficient service level for employees and improve efficiency.
  • There is a need for technology convergence or project convergence

The final conclusion: a microfront-end approach that fits your project needs is best.

(Photo from Internet)

Afterword.

Using single-SPA + system.js to realize the micro-front-end flexibility is very high, it can realize route hijacking, sub-application mount and uninstall, but it will encounter many problems, such as communication between applications, JS sandbox, common module extraction and other problems need to be realized by themselves, these are technical difficulties, but also can not be avoided work. Qiankun realized JS sandbox and inter-application communication based on the secondary packaging of single-SPA. If you are just starting or planning to start doing fusion now and are in the technology selection stage, if there are no specific customization needs, Qiankun can meet most scenarios. Our internal recommendation is to use Qiankun.

The answer from single-SPA’s official maintenance team is that Qiankun is a good microfront-end solution.

Refer to the article

  • qiankun
  • single-spa
  • Six or seven ways to implement front-end microservitization
  • “⚡ micro front end of actual combat: qiankun + Vue nuggets reconstruction planning | 🏆 technology project stage 4 essay…”
  • The Micro Front End you Must Know by 2020
  • Introduction to microfront-end
  • Practice of micro front end in Mi CRM system