Only then 2 Mid month , Guangzhou has gradually entered the summer ,—— Summer is always a time of anxiety . During the Spring Festival, I wrote the final chapter of the series of micro front end , Welcome to tile . If you're used to code directly , Let's skip to the practice section , Go straight to the code tutorial and play .

qiankun The principle and API Introduce

qiankun Is based on singlespa An upper application of the framework , It provides a complete life cycle , And some hook functions , Dynamically load and register micro applications through route matching , At the same time, it provides a series of api Manage and preload micro applications , It's relative to singlespa For me, progress is relatively great .

therefore ---qiankun Is essentially singlespa An encapsulation of , Based on what we saw in the previous section ,singlespa By outputting a manifest.json Dynamically construct by identifying the entry information script Rendering implementation of micro front-end applications , Similar to the picture below :

Take a look back. singlespa The core logic in the rendering process
1、 First of all, we have main( Lord app) child( Son app), Lord app only one , Son app There can be multiple
2、 secondly , Lord app In general, we can do it in index.html Inside , Write more space , That is, a few more div
for example :

<div id=”react-app”></div>
<div id=”vue-app”></div>

3、 then , In our child On , We need to use it. webpack plug-in unit , Generate a... With all the dependent files that need to be loaded manifest.json

4、 Main application to load this manifest.json, Get specific js, Use script Tags put it on the main application , Rendering

stay qiankun This logic is basically encapsulated in , Let's just go through a few simple api You can control singlespa The more complex configuration and concept in .


import { registerMicroApps, start } from 'qiankun';
name: 'react app', // apply name
entry: '//localhost:7100', // Application entry , Applications need to add cors Options
container: '#yourContainer', // Apply separate appid Of div
activeRule: '/yourActiveRule', // Matching routing
name: 'vue app',
entry: { scripts: ['//localhost:7100/main.js'] },
container: '#yourContainer2',
activeRule: '/yourActiveRule2',


main It's a qiankun The main part of , It also does not limit the types of frameworks , It can be used react It can also be used. vue and angular, Only need entry.js Just register it inside .

In general main It's a common code , for example :
1、 Message triggers
2、 Public routing
3、 Permission triggers
4、 Storage, such as global management 、 The skin 、 User management and other public pages

You can also write the home page of the site here , Can speed up the loading of the main body

Life cycle


boostrap amount to init, The subapplication will call this method when it is loaded for the first time , In general, you can do some project initialization operations inside , for example


It is called every time it is loaded into a child application , like componentDidMount, In general, we have to put ReactDOM.render Such initialization functions are written in it , Every time mount Called when the render


This heel mount Just the opposite , Every time I log off / It is called when switching subapplications , Generally we are here ReactDOM.unmountComponentAtNode Log off the app , Then let out the container of the whole project


It's an optional life cycle , When the subapplication changes, it will call .

Route matching

There are two kinds of routing rules , You need to manually call the corresponding sub application rendering , Through a call loadMicroApp To mount a child application component , So you can do it main Configure subapplication like a normal application in view 了 .

import { loadMicroApp } from 'qiankun';
import React from 'react';
class App extends React.Component {
containerRef = React.createRef();
microApp = null;
componentDidMount() {
this.microApp = loadMicroApp(
{ name: 'app1', entry: '//localhost:1234', container: this.containerRef.current, props: { name: 'qiankun' } },
componentWillUnmount() {
componentDidUpdate() {
this.microApp.update({ name: 'kuitos' });
render() {
return <div ref={this.containerRef}></div>;

Handling styles

The sandbox

qiankun The sandbox mode is in start Of api It is opened in the configuration item

sandbox Options available

sandbox: true // true | false | { strictStyleIsolation?: boolean, experimentalStyleIsolation?: boolean }

By default, Sandbox can ensure style isolation between subapplications in single instance scenarios , But we can't make sure that the main application and the sub application 、 Or sub application style isolation of multi instance scenarios . When the configuration is { strictStyleIsolation: true } The strict style isolation mode is turned on . In this mode qiankun Each micro application container will be wrapped with a shadow dom node , So as to ensure that the style of micro application will not affect the overall situation .
shadow dom coco The great God wrote an article about this , I won't teach you how to make an axe

Style conflict resolution

qiankun Automatically isolate styles between micro applications ( With the sandbox open ), You can manually ensure the style isolation between the main application and the micro application . For example, add a prefix to all styles of the main application , Or if you use ant-design Such a component library , You can automatically add the specified prefix to the main application style through the configuration method in this document .

With antd For example :

To configure webpack modify less Variable

loader: 'less-loader',
+ options: {
+ modifyVars: {
+ '@ant-prefix': 'yourPrefix',
+ },
+ javascriptEnabled: true,
+ },

To configure antd ConfigProvider

import { ConfigProvider } from 'antd';
export const MyApp = () => (
<ConfigProvider prefixCls="yourPrefix">
<App />

webpack Configuration issues

The following configuration needs to be added to the micro application packaging tool :

 const packageName = require('./package.json').name;
module.exports = {
output: {
library: `${packageName}-[name]`,
libraryTarget: 'umd',
jsonpFunction: `webpackJsonp_${packageName}`,

qiankun practice -react Micro front end applications

start , Get ready 2 individual react application

Direct use create-react-app Create two app application

npx create-react-app main-app
npx create-react-app micro-app

You can get a folder with two items

We use it main Master application ,micro Do sub applications , According to our api, Only one sub application needs to be configured register You can introduce sub applications
The sub application needs to call out webpack To configure ,create-react-app Manual configuration is not allowed by default , Just use the command
Get into micro-app Folder directory to run (create-react-app Also have overload To change the configuration , Here, for convenience, you can call it directly by command ):

npm run eject

In this way, the preparation work for the project is ready .

Sub application configuration

There are two steps to configure subapplication , One is life cycle configuration . Let's write a life cycle function and put it in main.js in :

And then we put reactDom.render Put it in mount Call in life cycle , Give Way qiankun When you're ready to load mount Then initialize the application :

unmount You can't forget the logout operation of :

We change the root node of the app all at once id, Refer to it in the parent application ( Don't forget to html It also needs to be changed ):

Finally, put webpack Modify the configuration in :
1、 modify devserver Support cors Modify the port
headers: { 'Access-Control-Allow-Origin': '*', }

2、 Modify and add bundle Export of , stay webpack.config.js Increase the configuration :

Parent application configuration

Then we can go to main Application , The first thing to register is

npm install qiankun --save

And then in main file index.js Register the subapplication in :

Don't forget we still need to be in public/index.html Write a div Containers ,id It's the one we used id, Rendering used to host subapplications :

Then we can start running and have a look :

The successful running , Just change it micro Let's see the effect :

Next, we need to deal with the problem of routing jump .

The practice of routing

As mentioned above , stay react Use in qiankun have access to apiloadMicroApp, Here we also use it to deal with route hops .
We are mainly in main-app In the operation :
First new micro-app Of view file ( Create a new app for each additional sub app ):

And then use react-router Direct configuration :
because create-react-app By default, it is not provided directly react-router, Let's go to the next one

npm install react-router react-router-dom --save

It's over index.js Long like this :

Try again :

Be accomplished !

Conclusion and source code

Compared to what we saw last time singlespa It's a lot easier to configure , And more straightforward , New sub applications are more seamless .
need demo Source code students private letter me oh

Application scenarios and pits

pit - Static resource problem solving

After the micro application is packaged css If the loading path used is relative path , It can lead to css Font file and image loading in 404.

and css Once the file is packaged , You can't change it dynamically publicPath To fix the path of the font file and background image .

There are three main solutions :

  • All images and other static resources are uploaded to cdn,css Directly quoted in cdn Address ( recommend )
  • With the help of webpack Of url-loader Package font files and images into base64( It is suitable for small font files and pictures )( recommend )
  • Use absolute address ,nginx Set static directory in


qiankun The overall idea is to compare ok Of , It greatly simplifies singlespa The use of logic , Let the threshold of micro front end become lower , But it still has some disadvantages , For example, part api There are always puzzling questions , for example api Documents are not particularly intuitive, etc , These are areas for improvement . And for the micro front end , Be able to do technology stack independent 、 Gradually upgrade old projects 、 Separation of different services and other functions can already give full play to its maximum value .

【 Microfront 】 The final chapter of micro front end -qiankun Guide and more related articles on the overall exploration of micro front end

  1. 【 Use guide 】WijmoJS Front end development kit

    For the convenience of the majority of front-end developers better use WijmoJS Front end development kit , Vineyard has launched WijmoJS Use guide , This guide describes in detail how to put WijmoJS All kinds of powerful functions apply to your own Web In the project , help ...

  2. Zero basis transfer web front end , How to learn efficiently web front end

    web The knowledge content of front-end development will be very broad , Although it's mainly HTML.CSS and JavaScript These basic knowledge points , But preschool development in addition to learning these basic knowledge , Students also need to extend and study deeply on this , And the Internet age is not ...

  3. web Front end learning tribes 22 Group to share with the need for front-end training projects

    Front end learning is still very interesting , Can quickly start, and then develop some fun projects to practice , Online can also grasp a large number of small projects on front-end development , But there are still novices who don't know what to do when they are learning , And how to do it , therefore , Just sort out some front-end project tutorials , ...

  4. Chris Richardson Micro service translation : Refactoring single service to micro service

    Chris Richardson Micro service series translation complete 7 Article links : Introduction to microservice Building the use of microservices API gateway The process communication of constructing microservice architecture Service discovery in microservice architecture Event driven data management for microservices Microservice deployment ...

  5. Web Front end development best practices (1): Front end development overview

    introduction I started from 07 I started to enter the blog Garden in , From the beginning of reading other people's articles to trying to express their own views on Technology . so to speak , Blog Garden is a major platform for me to participate in technical discussions . In the meantime , As the breadth and depth of access to technology increases , Also wrote some and got ...

  6. Web Front end development best practices (2): Front end code refactoring

    Preface Code refactoring is a hot topic in the industry , Refactoring refers to modifying the source code without changing the external behavior of the code , So before refactoring, we need to consider how to ensure that the external behavior does not change after refactoring . For back-end code , It can be done through a lot of automated testing ...

  7. Web Front end development best practices (3): Compression and merging of front-end code and resources

    Generally when the website is published , It compresses the front end HTML.CSS.JavaScript Code and used resource files ( Mainly picture files ), The purpose is to speed up the transmission of files in the network , Let the web show faster . Of course ,CDN distribution . Caching is also a way to speed up code or resources ...

  8. front end MVC Vue2 Learning summary ( 8、 ... and )—— Front-end routing

    Routing is based on different url Address shows different content or pages , Early routing was based on the back end url Come on reload Page implementation , Back end control routing . Later, the page became more and more complex , The pressure on the server is increasing , With AJAX( Asynchronous refresh technology ...

  9. React Is there a way to make money at the front end ?《React+Redux Front end development practice 》 start to learn sth.

    No more learning React It really can't keep up with the big front end , At present, almost all the front-end recruitment conditions are proficient React Priority , Look at the dragnet React Salary , All are 15K-20K, This summer vacation , It has to move . If you are familiar with JavaScript ...

  10. Web What are the three main front-end frameworks ?Web Front end prospects and employment situation

    In the last decade ,IT The industry is booming , A lot of new careers have been created , for example UI The designer . Development Engineer . Software test engineer and so on , Among the many high-profile freshmen occupations ,Web Front end engineers are one of them . that Web What are the three main front-end frameworks ? One .We ...

Random recommendation

  1. SQL Modify the default backup and recovery path of the database

    Every time you do data recovery and backup , spot Add file , The system will automatically assign to a default path , yes SQL Installation directory , But my database is not backed up here , It's a bit of a hassle to change every time . Pictured above , There are three ways to change this . Method 1 : Find the registry , hand ...

  2. Spring bean Implement initialization 、 The method and sequence of destruction

    Spring  allow  Bean  Perform specific actions after initialization and before destruction , There are three common methods : Using annotations , Add to the specified method @PostConstruct or @PreDestroy Annotation to determine whether the method is after initialization or ...

  3. Page zooming on FLASH Influence

    At present, new , And upgraded browsers , All of them have the function of page enlargement , These functions are right FLASH Influential , Performance in flash In obtaining stage.stageWidth when , The value will change proportionally I am using flex4.6 When developing , Self determination ...

  4. 【VS2013】 Set up Nuget agent

    @tags "visual studio 2013" nuget vs2013 of use nuget It must be a wonderful thing , It's like java with maven To install all kinds of packages . Sometimes the Internet is bad ,nu ...

  5. Codeforces Beta Round #1

    A topic , Water problem . B It's also a water problem , It's troublesome , I saw it in the team game a few days ago , Water problem how water can pass . C topic The question : Give a positive result n Three points on an edge , Find the smallest positive n The area of the edge . I seem to have seen this question before . There's no progress in thinking , It's enumeration n, By spinning a ...

  6. EIGR The nonequivalent equilibrium of P

    DUAL Algorithm ( Discrete update algorithm or diffusion update algorithm ) To configure 1. First configuration R1 Of IP R1(config)#inter f0/0 R1(config-if)#ip address 255.25 ...

  7. 【 turn 】 Set up TextView Writing in the middle

    Original website :http://blog.csdn.net/lanpy88/article/details/6616924 Yes 2 There are two ways to set TextView Writing in the middle : One : stay xml File settings :android: ...

  8. javascript: Sports frame

    function startMove(obj,json,fnEnd) { clearInterval(obj.timer);// Clear timer obj.timer=setInterval(function ...

  9. HDU1789 Doing Homework again

    Basic monotone queue : #include<cstdio> #include<cstdlib> #include<iostream> #include<algorith ...

  10. Test blog diary Day03-11.17 Japan —— Zhao Tianyu —— The use and configuration of Zen

    It's said to find out about Zen in Wikipedia first , I found that there is a detailed introduction to the project management software of Zen , Then the related introduction is sorted out and written into the document , In the introduction of Zen, there is also a download address and installation . (1) The basic situation of the software a. Chinese name : Zen project management ...