What is a micro front end
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 also run, develop and deploy independently.
Why do you need a micro front end
- Split refinement
The current front-end project usually takes the form of a SPA, where all the relevant pages for an application are in a single project. With the continuous iteration of the project, the maintenance cost will become higher and higher, and it is easy to “affect the whole body” dilemma. The significance of the micro front end is to break down the project into several sub-projects that can be deployed independently of each other.
- Compatible technology stack
Stack incompatibilities are also a headache in traditional front-end development, and we often give in to stack incompatibilities. Under the micro-front-end structure, the sub-projects of different technology stacks can coexist harmoniously
- Reduce migration costs
Another advantage of the micro front end is the ability to integrate existing projects at low cost. Because subprojects are independent, existing projects can be migrated to the new project with minimal effort
What is Qiankun
Qiankun is a single-SPa-based microfront-end implementation library that aims to make it easier and painless to build a production-ready microfront-end architecture system. First let’s take a look at what single-SPA is.
single-spa
Single-spa is a JavaScript front-end solution for front-end microservitization, and is one of the earliest microfront-end integration solutions.
In simple terms, single-SPA treats the child app as a spa page. The primary app loads and displays different child app resources using route matching. Child apps can be loaded, initialized, mounted, unmounted, and unloaded. Single-spa provides hook functions for these processes through a “lifecycle.”
Back to Qianhun, qianhun is a secondary development based on single-SPA, which adds more features on top of single-SPA, and does a good job of packaging, greatly lowering the threshold of entry to the micro front end.
Use Qiankun to realize the micro front end
Provides a tutorial qiankun.umijs.org/zh/guide/ge in official document…
Base reconstruction
1. Install qinakun
Yarn Add Qiankun or NPM I Qiankun-s
2. Sign up for microapps
import { registerMicroApps, start } from 'qiankun';
registerMicroApps([
{
name: 'react app'.// app name registered
entry: '//localhost:7100'.container: '#yourContainer'.activeRule: '/yourActiveRule'}, {name: 'vue app'.entry: { scripts: ['//localhost:7100/main.js']},container: '#yourContainer2'.activeRule: '/yourActiveRule2',}]); start();Copy the code
RegisterMicroApps is used to register the microapplication information. When the base route matches the activeRule, the base gets the microapplication from the entry, renders it to the Container, and invokes the microapplication lifecycle.
If the microapplication load is not matched by route, you can also choose to manually load the microapplication
import { loadMicroApp } from 'qiankun';
loadMicroApp({
name: 'app'.entry: '//localhost:7100'.container: '#yourContainer'});Copy the code
RegistrableApp
-
Name – string – Specifies the name of the micro-application. Each micro-application must be unique. This parameter is mandatory.
-
entry – string | { scripts? : string[]; styles? : string[]; html? : string} – Mandatory, microapplication entry.
-
The container – string | HTMLElement – will be chosen, the application of micro selector of the container node or Element instances. Container: ‘#root’ or container: document.querySelector(‘#root’).
-
ActiveRule – string | (location: the location) = > Boolean | Array < string | (location: the location) = > Boolean > – will be chosen, the application of active rules.
-
Loader – (loading: Boolean) => void – Optional, this method is called when loading state changes.
-
Props – Object – Optional data that the main application needs to pass to the micro-application.
Microapplication modification
Exporting hook functions
Microapplications do not require installation dependencies, and the main purpose of the transformation is to “expose” the rudiments of microapplications. Export the bootstrap, mount, and unmount lifecycle hooks in your own entry file for the main application to call.
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import 'antd/dist/antd.css';
import './public_path';
import i18n from 'i18next';
// Encapsulate the rendering process for use
function render(props: any) {
const { container } = props;
ReactDOM.render(
<React.StrictMode>
<App></App>
</React.StrictMode>,
container
? container.querySelector('#root')
: document.querySelector('#root')); }// Render normally if it is not loaded by the base
if(! (window as any).__POWERED_BY_QIANKUN__) {
render({});
}
// Bootstrap will only be called once during the micro-application initialization. The next time the micro-application re-enters, the mount hook will be called directly. Bootstrap will not be triggered again.
// Usually we can do some initialization of global variables here, such as the application level cache that will not be destroyed in the unmount phase, etc.
export async function bootstrap() {
console.log('react app bootstraped');
}
// The mount method is called every time the application is entered. This is where we usually trigger the application's render method and listen for messages from the base
export async function mount(props: any) {
console.log('props from main framework', props);
render(props);
props.onGlobalStateChange((state: any, prev: any) = > {
console.log('Child Application Listener',state,prev);
});
}
export async function unmount(props: any) {
const { container } = props;
ReactDOM.unmountComponentAtNode(
container
? container.querySelector('#root')
: document.querySelector('#root')); }export async function update(props: any) {
console.log('update props', props);
}
Copy the code
Modify the WebPack configuration
The WebPack was modified to allow the base to correctly recognize some of the information exposed by the microapplication when packaging.
Add the following configuration to Webpack
const packageName = require('./package.json').name;
module.exports = {
output: {
library: `${packageName}-[name]`.libraryTarget: 'umd'.jsonpFunction: `webpackJsonp_${packageName}`,}};Copy the code
(Note: For Webpackage 5, jsonpFunction is changed to chunkLoadingGlobal)
Configuring a Public Directory
Public_path. js is added in SRC and imported in the entry
if (window.__POWERED_BY_QIANKUN__) {
__webpack_public_path__ = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__;
}
Copy the code
Routing modification
Microapplication routes must be configured with activeRule routes; otherwise, microapplication routes cannot be correctly matched
<BrowserRouter basename="/react-qiankun-micro">
Copy the code
The source code to share
At this stage, a basic qiankun microapplication shell was put up. I made a simple framework on this basis, and the effect is shown in the picture. I hope it can be helpful to everyone
React Micro app: github.com/yuzhuohao/r… React main app: github.com/yuzhuohao/r…