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

itread01 2021-02-23 02:49:43
micro end final chapter micro


order

  That's it 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 make bricks . If you're used to code directly , Let's skip to the practice section , Go straight to the code tutorial and play .

If you haven't read the previous chapters Here's the link :

Micro front end reward

Micro front end reward 2 -singlespa Practice

qiankun The principle and API Introduce

qiankun 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 In essence singlespa A package of , Based on what we saw in the last section ,singlespa It's by outputting a manifest.json Dynamically construct by identifying entry information script Rendering implementation of micro front-end applications , Similar to the figure below :

Review 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、 And then , In our child On , We need to use webpack Plug in , Generate a file with all the dependencies that need to be loaded manifest.json

4、 The main application loads this manifest.json, Get specific js, Use script Tags put it on the main application , Render

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', // Application name entry: '//localhost:7100', // Application Portal , 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 The purpose of is to store common code , for example :
1、 Message triggers
2、 Public routing
3、 Permission triggers
4、 Storage, such as global management 、 panel 、 User management and other public pages

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

 

Life cycle

 

bootstrap

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

 

mount

It is called every time it is loaded into a subapplication , like componentDidMount, In general, we have to put ReactDOM.render This initialization function is written in it , Every time mount When you call render

 

unmount

This is with mount Just the opposite , Every time I log out / Call it when you switch subapplications , Generally we are here ReactDOM.unmountComponentAtNode Log out of this 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 call the corresponding sub application rendering manually , Through a name called loadMicroApp To mount a child application component , In this way, you can be in 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>; }}

 

Processing style

 

The sandbox

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

sandbox Options are optional

 

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

By default, Sandbox can ensure style isolation between sub applications of single instance scenarios , But we can't make sure that the main application and the sub application 、 Or sub application style isolation of multiple scenarios . When configured to { 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 global .
shadow dom coco The great God wrote an article about this , I don't want to be a good teacher
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 catalog , You can automatically add the specified prefix to the main application style through the configuration method in this file .

With antd For example :

To configure webpack modify less Variables

 

{ 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 problem

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 , Prepare for 2 One react Apply

Direct use create-react-app Create two app Apply

 

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

You can get a folder with two projects


We use 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 The default is not allowed to be configured manually , Just use the command
Enter micro-app The folder directory of (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 for the project will be done .

 

Subapplication configuration

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

Then we put reactDom.render Put it in mount Life cycle calls , Let 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 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 In application , The first thing to register is

npm install qiankun --save

And then in main Archives 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're using id, Rendering used to host subapplications :

 

 

 

Then we can go ahead and have a look :

 

 

 

Successful execution , 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 Archives ( Create a new app for each additional sub app ):

 

 

 

Then use react-router Direct configuration :
Because of create-react-app Default is not directly provided 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 The students of the original code sent me a private letter

 

Application scenarios and pits

 

pit - Static resource problem solving

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

and css Once the files are packaged , You can't change it dynamically publicPath To fix the path of 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 ( Recommendation )
  • By means of webpack Of url-loader Package font files and pictures into base64( It is suitable for projects with small font files and pictures )( Recommendation )
  • Use absolute address ,nginx Set the static directory in

  

Conclusion

qiankun The overall idea is to compare ok Of , It greatly simplifies singlespa The logic of using , 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 Files are not particularly intuitive, etc , These are areas for improvement . And for micro front end , Be able to do technology stack independent 、 Gradually upgrade old projects 、 Separation of different services and other functions has been able to play its maximum value

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

  1. An inexperienced front-end engineer, what are the common problems when writing CSS?
  2. HttpServletRequest get URL (parameter, path, port number, protocol, etc.) details
  3. Springboot starts http2
  4. Enabling http2.0 in spring boot
  5. JQuery:JQuery基本语法,JQuery选择器,JQuery DOM,综合案例 复选框,综合案例 随机图片
  6. Using JavaScript in Safari browser history.back () the page will not refresh after returning to the previous page
  7. vue.js Error in win10 NPM install
  8. In less than two months, musk made more than $1 billion, more than Tesla's annual profit
  9. Springboot starts http2
  10. Vue event bus
  11. JQuery easy UI tutorial: custom data grid Pagination
  12. Using okhttp and okhttpgo to obtain onenet cloud platform data
  13. Vue3 component (IX) Vue + element plus + JSON = dynamic rendering form control
  14. HTTP 1. X learning notes: an authoritative guide to Web Performance
  15. Vue3 component (IX) Vue + element plus + JSON = dynamic rendering form control
  16. HTTP 1. X learning notes: an authoritative guide to Web Performance
  17. JQuery:JQuery基本语法,JQuery选择器,JQuery DOM,综合案例 复选框,综合案例 随机图片
  18. Event bubble and capture in JavaScript
  19. The root element is missing solution
  20. Event bubble and capture in JavaScript
  21. Configure the certificate to enable ngnix to publish the trusted website of HTTPS
  22. Javascript数据类型
  23. HTTP interface debugging tool! 48000 star HTTP command line client!
  24. Parameter encryption of front end URL link band
  25. HTTP interface debugging tool! 48000 star HTTP command line client!
  26. Three front end frameworks: data binding and data flow
  27. Reading Axios source code (1) -- exploring the realization of basic ability
  28. Event bubble and capture in JavaScript
  29. 【微前端】微前端最終章-qiankun指南以及微前端整體探索
  30. R & D solution e-Car front end monitoring system
  31. [JS] 877 - 35 wonderful knowledge of JavaScript, long experience!
  32. R & D solution e-Car front end monitoring system
  33. High performance nginx HTTPS tuning - how to speed up HTTPS by 30%
  34. 解决ajax跨域问题【5种解决方案】
  35. Top ten classic sorting of JavaScript
  36. HTTP 1. X learning notes: an authoritative guide to Web Performance
  37. Vue3 component (IX) Vue + element plus + JSON = dynamic rendering form control component
  38. My http / 1.1 is so slow!
  39. Why Vue uses asynchronous rendering
  40. The response status was 0. Check out the W3C XMLHttpRequest Level 2 spec for
  41. The tapable instance object hook of webpack4. X core tool library
  42. The tapable instance object hook of webpack4. X core tool library
  43. Using libcurl for HTTP communication in C + +
  44. Using libcurl for HTTP communication in C + +
  45. Using CSS variable in Vue
  46. Deeply understand the update of state and props in react
  47. No matter how fast the Internet is, it's useless! In addition to Baidu disk, there is this website slow to let you eat shriveled
  48. Baidu share does not support the solution of HTTPS
  49. [micro front end] the final chapter of micro front end - Qiankun guide and overall exploration of micro front end
  50. [micro front end] the final chapter of micro front end - Qiankun guide and overall exploration of micro front end
  51. Vue cli creates vue3 project
  52. Nginx reverse proxy for windows authentication using NTLM
  53. Rust tutorial: introduction to rust for JavaScript developers
  54. Deploying personal blog to Tencent cloud with serverless framework
  55. R & D solution e-Car front end monitoring system
  56. JavaScript advanced learning
  57. Spend 1 minute to master these 5 ppt tips, courseware making less detours
  58. Vue: vuex persistent state
  59. React native gets the current network state of the device Netinfo
  60. High performance nginx HTTPS tuning - how to speed up HTTPS by 30%