First experience of Qiankun micro front end

JavaScript Art 2021-06-17 19:24:16
experience qiankun micro end


What is a micro front end

In plain English , Micro front end can deploy different parts of a large application independently , The parts are independent of each other , The ability to deploy independently allows them to build isolated or loosely coupled services . That is, the single page front-end application is transformed from a single single single application into a multi small front-end application .

The core design concept of micro front end

  • Technology stack independent The main framework does not limit access to the application technology stack , Micro applications have full autonomy
  • Independent development 、 Independent deployment The micro application warehouse is independent , The front and rear end can be developed independently , After the deployment, the main framework automatically completes the synchronization update
  • Incremental upgrade In the face of all kinds of complex scenes , It is usually difficult for us to upgrade or refactor an existing system , And micro front end is a very good means and strategy to implement gradual reconfiguration
  • When running independently State isolation between each micro application , Runtime state not shared

The core goal of the micro front end is to split the giant application into several independent sub applications

qiankun It's based on single-spa Micro front end implementation library of

qiankun Quick start

qiankun Official website https://qiankun.umijs.org/zh/ Specific code examples github There are some qiankun Example code for https://github.com/zhjing1019/QianKunDemo

Main application

The main application is not limited to technology stack , Just provide a container DOM, Then register the micro app and start that will do .

yarn add qiankun # perhaps npm i qiankun -S
import { registerMicroApps, start } from 'qiankun'; /** * Register the micro application in the main application */ registerMicroApps([ { name: 'vue sub-app1', entry: '//localhost:7100/sub.html', container: '#yourContainer', activeRule: '/yourActiveRule', }, { name: 'vue sub-app2', entry: '//localhost:7101', container: '#yourContainer', activeRule: '/yourActiveRule', }, ], { beforeLoad: [ app => { console.log('before load', app); }, ], beforeMount: [ app => { console.log('before mount', app); }, ], afterMount: [ app => { console.log('after mount', app); }, ], afterUnmount: [ app => { console.log('after unload', app); app.render({appContent: '', loading: false}); }, ], } ); start();
Sign up for micro apps

When the micro application information is registered , Once the browser url change , Will automatically trigger qiankun The matching logic of , all activeRule The micro application on the rule matching will be inserted into the specified container in , At the same time, call the life cycle hook exposed by micro application in turn Micro applications need to be in their own portal js ( It's usually what you configure webpack Of entry js) export bootstrap、mount、unmount Three life cycle hooks , For the main application to call at the right time . Micro applications can be accessed without additional installation of any other dependencies qiankun Main application .

/** * bootstrap It will only be called once when the micro application is initialized , The next time the micro application re enters, it will directly call mount hook , No more triggers bootstrap. * Usually we can do some initialization of global variables here , For example, not in unmount Phase is destroyed by the application level cache and so on . */ export async function bootstrap() { console.log('react app bootstraped'); } /** * Every time the application enters, it calls mount Method , Usually we trigger the applied rendering method here */ export async function mount(props) { ReactDOM.render(<App />, props.container ? props.container.querySelector('#root') : document.getElementById('root')); } /** * Apply every time Cut out / uninstall Method to be called , Usually here we will unload the application instance of micro application */ export async function unmount(props) { ReactDOM.unmountComponentAtNode( props.container ? props.container.querySelector('#root') : document.getElementById('root'), ); } /** * Optional lifecycle hooks , Use only loadMicroApp It will take effect when the micro application is loaded in this mode */ export async function update(props) { console.log('update props', props); }

The main application communicates with the sub application project

initGloabalState(state) Define the global state , And return the communication method , The official suggestion is to use it in the main application , Micro application through props Get the communication method . MicroAppStateActions onGlobalStateChange: (callback: OnGlobalStateChangeCallback, fireImmediately?: boolean) => void, Monitor the global state in the current application , There is a change trigger callback,fireImmediately = true Immediately triggered callback setGlobalState: (state: Record) => boolean, Set global state by one level property , In micro application, you can only modify the existing first level attributes offGlobalStateChange: () => boolean, Remove the status monitor of the current application , Microapplication umount Call by default

Main application :

import { initGlobalState, MicroAppStateActions } from 'qiankun'; // initialization state const actions: MicroAppStateActions = initGlobalState(state); actions.onGlobalStateChange((state, prev) => { // state: The changed state ; prev The state before the change console.log(state, prev); }); actions.setGlobalState(state); actions.offGlobalStateChange();

Subapplication

// From life cycle mount Get the communication method in , Usage and master Agreement export function mount(props) { props.onGlobalStateChange((state, prev) => { // state: The changed state ; prev The state before the change console.log(state, prev); }); props.setGlobalState(state); }
js Variable isolation

Every subapplication has its own life cycle , At the same time , Only one instance of the child application will take effect .js Sandbox encased in qiankun In the life cycle of . When a child application is destroyed , Its js The sandbox is destroyed . The only deficiency is ,window The object of , Unable to isolate , It's better not to bind prototypes .

css Pollution

1、scoped( Temporary solutions : The style of the main application uses special class perhaps scoped) 2、 The main application can be set by prefixCls To avoid conflict in a different way 3、 To configure webpack modify less Variable

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

qiankun Detailed analysis of the source code https://www.jianshu.com/p/db08174fa4fc?utm_campaign=shakespeare

This article is from WeChat official account. - javascript art (gh_4e5484fd6b52) , author :zhangjing

The source and reprint of the original text are detailed in the text , If there is any infringement , Please contact the [email protected] Delete .

Original publication time : 2021-04-12

Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .

版权声明
本文为[JavaScript Art]所创,转载请带上原文链接,感谢
https://qdmana.com/2021/05/20210528145604827s.html

  1. HTML + CSS + JavaScript to achieve cool Fireworks (cloud like particle text 3D opening)
  2. HTML + CSS + JavaScript realizes 520 advertising love tree (including music), which is necessary for programmers to express themselves
  3. Solve the problem of Web front-end deployment server (it can be deployed online without a server)
  4. HTML + CSS + JS make wedding countdown web page template (520 / Tanabata Valentine's Day / programmer advertisement)
  5. What else can driverless minibus do besides "Park connection"?
  6. Cloud native leads the era of all cloud development
  7. NRM mirror source management tool
  8. Bring it to you, flex Jiugong
  9. Lolstyle UI component development practice (II) -- button group component
  10. Deconstruction assignment in ES6
  11. Luo 2 peerless Tang clan was officially launched. The official gave a key point, and the broadcast time was implied
  12. 20初识前端HTML(1)
  13. 当新零售遇上 Serverless
  14. 20 initial knowledge of front-end HTML (1)
  15. When new retail meets serverless
  16. [golang] - go into go language lesson 5 type conversion
  17. [golang] - go into go language lesson 6 conditional expression
  18. HTML5(八)——SVG 之 path 详解
  19. HTML5 (8) -- detailed explanation of SVG path
  20. 需要开通VIP以后页面内容才能复制怎么办?控制台禁用javascript即可
  21. Web前端|CSS入门教程(超详细的CSS使用讲解,适合前端初学者)
  22. 实践积累 —— 用Vue3简单写一个单行横向滚动组件
  23. Serverless 全能选手,再下一城
  24. What if you need to open a VIP to copy the page content? Just disable JavaScript on the console
  25. Web front end | CSS introductory tutorial (super detailed CSS explanation, suitable for front-end beginners)
  26. Practice accumulation - write a single line horizontal scroll component simply with vue3
  27. Dili Reba is thin again. She looks elegant and high in a strapless hollow skirt, and her "palm waist" is beautiful to a new height
  28. Serverless all-round player, next city
  29. The difference between MySQL semi synchronous replication and lossless semi synchronous replication
  30. Vue表单设计器的终极解决方案
  31. The ultimate solution for Vue form designer
  32. Nginx从理论到实践超详细笔记
  33. Yu Shuxin's red backless swimsuit is split to the waist and tail, with a concave convex figure and excessive color matching, and his face is white to dazzling
  34. Nginx ultra detailed notes from theory to practice
  35. 【动画消消乐|CSS】086.炫酷水波浪Loading过渡动画
  36. typecho全站启用https
  37. CCTV has another popular employee. The off-site interpretation is very professional, and the appearance ability is no less than that of Wang Bingbing
  38. [animation Xiaole | CSS] 086. Cool water wave loading transition animation
  39. Enable HTTPS in Typecho
  40. 50天用JavaScript完成50个web项目,我学到了什么?
  41. 根据JavaScript中原生的XMLHttpRequest实现jQuery的Ajax
  42. What have I learned from completing 50 web projects with JavaScript in 50 days?
  43. "My neighbor doesn't grow up" has hit the whole network. There are countless horse music circles, and actor Zhou Xiaochuan has successfully made a circle
  44. 根据JavaScript中原生的XMLHttpRequest实现jQuery的Ajax
  45. Implement the Ajax of jQuery according to the native XMLHttpRequest in JavaScript
  46. Implement the Ajax of jQuery according to the native XMLHttpRequest in JavaScript
  47. 30 + women still wear less T-shirts and jeans. If they wear them like stars, they will lose weight
  48. 数栈技术分享前端篇:TS,看你哪里逃~
  49. Several stack technology sharing front end: TS, see where you escape~
  50. 舍弃Kong和Nginx,Apache APISIX 在趣链科技 BaaS 平台的落地实践
  51. Abandon the landing practice of Kong and nginx, Apache apisik on the baas platform of fun chain technology
  52. 浪迹天涯king教你用elementui做复杂的表格,去处理报表数据(合并表头,合并表体行和列)
  53. 前端HTML两万字图文大总结,快来看看你会多少!【️熬夜整理&建议收藏️】
  54. Wandering around the world king teaches you to use elementui to make complex tables and process report data (merge header, merge table body rows and columns)
  55. 路由刷新数据丢失 - vuex数据读取的问题
  56. Front end HTML 20000 word graphic summary, come and see how much you can【 Stay up late to sort out & suggestions]
  57. Route refresh data loss - vuex data reading problem
  58. Systemctl系统启动Nginx服务脚本
  59. Systemctl system startup nginx service script
  60. sleepless