[micro front end] the final chapter of micro front end - Qiankun guide and overall exploration of micro front end

Zhang Taifeng 2021-02-23 01:52:34
micro end final chapter micro


order

  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 :
avatar

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 .

 

register

 

import { registerMicroApps, start } from 'qiankun';
registerMicroApps([
{
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',
},
]);
start();

 

main

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

 

bootstrap

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

 

mount

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

 

unmount

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

 

update

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() {
this.microApp.unmount();
}
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

 

start({
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
https://www.cnblogs.com/coco1s/p/5711795.html

 

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 />
</ConfigProvider>
);

 

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

  

Conclusion

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 .

版权声明
本文为[Zhang Taifeng]所创,转载请带上原文链接,感谢
https://qdmana.com/2021/02/20210222202532565v.html

  1. vue判断elementui中el-form是否更新变化,变化就提示是否保存,没变就直接离开
  2. 算法题:两数之和——JavaScript及Java实现
  3. 高性能 Nginx HTTPS 调优
  4. Why Vue uses asynchronous rendering
  5. day 31 jQuery进阶
  6. day 30 jQuery
  7. CSS whimsy -- using background to create all kinds of wonderful backgrounds
  8. Why are more and more people learning front end?
  9. What do you do with 4K front-end development?
  10. 8 years of front-end development knowledge precipitation (do not know how many words, keep writing it...)
  11. What is the annual salary of a good web front end?
  12. Front end novice tutorial! How to get started with web front end
  13. Will the front end have a future?
  14. Is the front end hard to learn?
  15. Seven new Vue combat skills to improve efficiency in 2021!
  16. Is front end learning difficult?
  17. How about the process of Web front-end development and self-study?
  18. Front end learning route from zero basis to proficient
  19. What is the basis of learning front end?
  20. What knowledge points need to be learned for self-study front end? How long can I become a front-end Engineer?
  21. An inexperienced front-end engineer, what are the common problems when writing CSS?
  22. HttpServletRequest get URL (parameter, path, port number, protocol, etc.) details
  23. Springboot starts http2
  24. Enabling http2.0 in spring boot
  25. JQuery:JQuery基本语法,JQuery选择器,JQuery DOM,综合案例 复选框,综合案例 随机图片
  26. Using JavaScript in Safari browser history.back () the page will not refresh after returning to the previous page
  27. vue.js Error in win10 NPM install
  28. In less than two months, musk made more than $1 billion, more than Tesla's annual profit
  29. Springboot starts http2
  30. Vue event bus
  31. JQuery easy UI tutorial: custom data grid Pagination
  32. Using okhttp and okhttpgo to obtain onenet cloud platform data
  33. Vue3 component (IX) Vue + element plus + JSON = dynamic rendering form control
  34. HTTP 1. X learning notes: an authoritative guide to Web Performance
  35. Vue3 component (IX) Vue + element plus + JSON = dynamic rendering form control
  36. HTTP 1. X learning notes: an authoritative guide to Web Performance
  37. JQuery:JQuery基本语法,JQuery选择器,JQuery DOM,综合案例 复选框,综合案例 随机图片
  38. Event bubble and capture in JavaScript
  39. The root element is missing solution
  40. Event bubble and capture in JavaScript
  41. Configure the certificate to enable ngnix to publish the trusted website of HTTPS
  42. Javascript数据类型
  43. HTTP interface debugging tool! 48000 star HTTP command line client!
  44. Parameter encryption of front end URL link band
  45. HTTP interface debugging tool! 48000 star HTTP command line client!
  46. Three front end frameworks: data binding and data flow
  47. Reading Axios source code (1) -- exploring the realization of basic ability
  48. Event bubble and capture in JavaScript
  49. 【微前端】微前端最終章-qiankun指南以及微前端整體探索
  50. R & D solution e-Car front end monitoring system
  51. [JS] 877 - 35 wonderful knowledge of JavaScript, long experience!
  52. R & D solution e-Car front end monitoring system
  53. High performance nginx HTTPS tuning - how to speed up HTTPS by 30%
  54. 解决ajax跨域问题【5种解决方案】
  55. Top ten classic sorting of JavaScript
  56. HTTP 1. X learning notes: an authoritative guide to Web Performance
  57. Vue3 component (IX) Vue + element plus + JSON = dynamic rendering form control component
  58. My http / 1.1 is so slow!
  59. Why Vue uses asynchronous rendering
  60. The response status was 0. Check out the W3C XMLHttpRequest Level 2 spec for