Talking about the application practice of micro front end in Didi car service
Posted May 28, 2020 • 14 min read
Introduction:If you take stock of the hottest front-end technology in 2019, then the micro front end will definitely have its place. But most people are still in a state of ignorance about the upstart of the micro front end architecture. This article will introduce the past and present of the micro front end in detail and take you to understand how the micro front end architecture has evolved step by step from the actual needs And a small orange car service based on the micro front end refined a set of middle and backstage system construction practice.
1 . What is a micro front end
The concept of micro front end was originally proposed corresponding to the concept of micro service. The core idea of micro service is to split a large single application into a group of small services based on business capabilities. Each service is an independent process and can Independent deployment, no unified technology stack for centralized management, only need to perform lightweight communication to complete business demands. The micro front end is such an architectural model similar to micro services. It applies the core idea of micro services to the browser side, that is, a single complex(large-scale) front-end application is converted into multiple small front-end applications, each small front-end application It has nothing to do with the technology stack, and can be independently developed and deployed. Of course, the split also requires a mature communication mechanism to connect all applications in series, which can not only ensure application autonomy but also ensure application contact, and jointly improve development with better coordination. effectiveness.
In summary, under the background of front-end integration, the micro front end uses technical means to achieve an engineering architecture solution for business layer application aggregation and technical layer application autonomy to achieve a rich and powerful front-end application.
2 . Why do we need a micro front end
Does it still feel a bit hazy? It does n t matter. Based on any technology, you need to rely on business principles. Let s take a simple and easy-to-understand example to help you understand why the front-end needs a micro-front-end architecture:
Many years ago, Xiaohong and Xiaolan decided to start a business and opened an online store. The two people hit it off and quickly designed a prototype version 1.0. Using the most original Jquery and Html, they produced a set of shopping sites for users and operations. The displayed management background:
In order to facilitate understanding, we first ignore the shopping system at the front desk and only focus on the back-end management system. Because only the most basic shopping needs need to be met in the early stage of the project, all the management needs at that time were concentrated in a management system, and the code was gathered in a warehouse. The structure is as follows:
Xiaohong and Xiaolan quickly brought the 1.0 version of the online store to the market. Because they seized the opportunity, everyone loved the feeling of shopping without going out, and the two quickly made a sum of money.
Later, as the business grew bigger and bigger, commodity management was gradually divided into selected commodity management and ordinary commodity management. Inventory management was divided into partner inventory and self-operated inventory. Order management and user management also became larger and larger. :
It can be clearly seen that with the complexity of the business, the management of each module becomes more and more bloated, and it becomes more and more troublesome for all teams to maintain different functions in a system, so Xiaohong and Xiaolan decided to go online 2.0 Version, the entire background management system is decoupled and split, and different teams maintain different modules. Team A is only responsible for commodity management, team B is only responsible for inventory management, and the remaining modules are similar. Development without interference.
In the 2.0 mode, when the business is getting bigger and bigger, Xiaohong and Xiaolan decide to set up two marketing and channel teams to carry out some marketing activities and channel activities respectively, and the background management system also needs to add a channel management and marketing management module. Following the logic of the above decoupling, the two teams created a new channel system and marketing system to manage them separately. Everyone produced their own codes and maintained their own systems, which greatly enhanced their scalability.
At the same time, with the development of front-end technology, the frameworks of Jquery and Html are gradually lagging behind. Angular, React, Vue and other single-page applications have emerged as the main force. Each team has gradually begun to reconstruct their own systems. The system uses the Vue framework, etc., and everyone is working towards the framework they are interested in. The state of individualism allows everyone to not interfere with each other. In this way, it meets the needs of the initial code decoupling.
Everything in the 2.0 mode looks perfect, but is it really perfect? Soon the problem came up:
First of all, I was struggling with operating classmates and product classmates who really used the background system. These students wanted to use the various functions of the background system, and their daily operations became constant switching, switching, and then switching systems. For example, if they want to list a new product, they need to go to the product management system to configure a series of information, then go to the inventory management system to query the corresponding product inventory, and finally go to the marketing system to configure the marketing activities of the product. The entire process needs to be constantly switched System, operating efficiency is greatly reduced.
Then, the development efficiency is greatly reduced. For example, all systems are based on the same set of login permission modules, but because they are deployed in different domain name environments, each system is developed repeatedly, as are similar gateway modules, log modules, and so on. Moreover, there are a large number of coupling functions between different systems, and a single code environment cannot reuse some existing code of other systems, which will cause various repetitive wheel behaviors.
What are the ways to allow each system to develop and deploy independently, choose its own technology stack, and can be closely linked and aggregated into a system for use by operating students and product students. The architecture of the micro front end came into being.
The core idea of the micro front end is to decompose a complete front end application into some smaller, granular, sub-applications that can be independently developed, tested, and deployed. The sub-applications are connected to each other through a weak communication mechanism. Poly single product.
Then the background management system of the entire electronic mall can be re-structured using the idea of micro front end, which is the 3.0 mode:
In this way, from the product dimension, all systems are integrated in a base system, users only need to log in once to switch between systems without refreshing, all functions are integrated together, which effectively improves operational efficiency; from the technical dimension See, each system does not need to rebuild the technology stack, it can still use the original technology stack, each team still maintains its own code base, independently deploys and goes online, and can share some common capabilities such as login and authentication , RBI, log analysis, etc., that ensures the migration of the legacy system, and aggregates the front-end applications to perfectly solve the problem of how to manage the application in the case of bloated applications.
I believe that through the above example, in the gradual evolution of a virtual e-commerce back-end system architecture, you should understand why the front end needs a micro front-end architecture. In summary, the micro front-end has the following advantages:
- Flexible aggregation of business into a system: Product function coupling, when facing users, multiple different business functions are coupled into a business system.
- Compatible with multiple technology stacks: Whether the technology stack is Vue, React, or Angular, it can run perfectly in a system.
- Independent development and deployment: The warehouses between the sub-applications are independent and can be developed independently. After deployment, the container layer will complete automatic synchronization updates.
- Reliance on resource reuse: Extract public resources that are dependent on different applications and load multiple parties at once to improve performance.
3 . Technical selection of micro front end
As mentioned above, why the micro front-end architecture is needed, then the technology selection is first introduced. First, a concept needs to be clarified. The micro front-end is an architectural idea, not specifically referring to a technology. It is that the current end business is developing to a certain scale Afterwards, an architectural model used to decompose the complexity can specifically consider the following types of selection:
This is one of the oldest micro-front-end technology implementations, and it is also the easiest to implement. Through the reverse proxy function of HTTP, the request is forwarded to the responding service after routing judgment. The advantage is that almost no modification or configuration is required. Just take a look at the nginx service, and the shortcomings are also obvious. There is no performance optimization at all. The system still needs to refresh the page to reload the resource file, but just piece together different applications from the surface.
Widgetization means that an application is compiled in advance by the developer in advance for complete and closed-loop all functions. Other applications can be directly embedded in the web page without any modification or compilation and can be run and displayed directly. In the early days of many applications, this was done by encapsulating their own applications into SDK packages. Users can load javascipt code remotely to generate corresponding components and embed them on the page. Later, with the popularity of npm, they gradually developed applications into NPM packages. The source code is released in the form of. The advantage of this is that it is flexible to deploy and package separately. The disadvantage is that if multiple application widgets are introduced, there may be problems of mutual interference, and communication between applications is difficult. Too many transformations are needed for legacy applications.
Self-made framework micro application service
Micro-application service means that the system exists in the form of a single tiny application at the beginning. Only when the system is running, these applications are loaded and merged by the system framework to form a complete system. Whether it is a react and vue framework based on a virtual tree, or an Angular framework based on Web Components, the prototype of all frameworks is inseparable from loading elements in html. Then, we only need to package and compile a single system into a micro application in advance. Introduce or create a DOM in the right place on the page, so that when the user operates, the application starts and the application can be uninstalled when the user switches, so the core of this micro-app service is the design of the loader, which can load and switch different applications in real time. It can effectively isolate applications to prevent mutual interference. Single-SPA is a relatively mature open source framework, which can integrate multiple different frameworks on a page, and even do not need to refresh the page when switching. It already supports React, Vue, Angular 1, Angular 2, Ember, etc. Wait, if you want to simply apply the engineering micro application, you can consider using this framework.
Of course, there is no silver bullet. The micro front end is not a panacea. No matter what kind of implementation, before considering the micro front end architecture, in addition to considering the benefits it brings, we must also consider the large number of risks and technical challenges that exist. E.g:
- How to distinguish between development environment and online environment after use
- How to isolate JS and avoid CSS conflicts
- Mechanism for sharing common resources between applications
- Third-party modules overlap
- Handle data acquisition and consider the user's initial loading status
- How to access permissions
- How to reduce the initial loading time
- How to test effectively
Therefore, the micro front end, like micro services, needs a series of technical reserves to truly enter practice. At present, the small orange car service combines with the actual business form to build a full-link product access platform, which solves the technical card points in the above micro front end, and provides a common solution for the construction of the middle and back office system.
4 . The practice of micro front end in car service
First introduce the background, the car service rental business line has a very high business complexity, and has experienced many business model exploration, integration and optimization. In the process of continuous exploration and adjustment of the business, the car rental business and the MIS system have formed a system of multiple divisions. At the same time, various independent systems such as procurement, marketing, and corporate fleets have also been newly built due to business-side demands There are more new independent systems on the business side planning and construction, which greatly exacerbates the cost of developing and maintaining these mid- and back-end systems.
To this end, the team decided to provide a set of micro front-end architecture based on the integration of LASS capabilities in the current group and car service environment, from page resources to micro applications to the unified ability of system-level construction and management, namely the Midway platform.
As mentioned above, the Midway platform is based on the concept of micro front-end architecture and uses the base mode to provide a main application that is the base as a unified entrance to the system, manages the life cycle of sub-applications and communication between applications, and provides core business functions such as users Login, unified authentication, navigation menu, route management and other functions, and direct the corresponding request to the corresponding service. The sub-application is specifically responsible for the business implementation of the sub-module, ignoring the technical stack, and developed and deployed independently by each team.
The bottom layer of Midway is based on single-spa. It isolates the style and scope between sub-applications. Through application registration, hook reference and other methods, it implements complete life cycle control of the accessed applications. It also provides application communication, public resource loading, Application on-demand loading, application pre-loading, log monitoring and other low-level functions, the following highlights introduce:
Midway calls the single-spa registerApplication method to register the micro-application, and supports the transfer of the asynchronous function loadApp(just return the Promise) and non-function type values. If it is a non-function type, it will actively convert, before and after the hook returns and the returned hook does some function construction:
- Added beforeUnmount, afterUnmount, beforeMount, afterMount, beforeLoad hooks to facilitate some processing before and after applying mount and load.
- Obtain static resources according to the single-page framework(Pegasus), add hooks and related configurations for the Pegasus page entry.js, etc.
- According to the entry type passed in when the application is registered, analyze and obtain the html, scripts, styles, id(Pegasus page) and other information of the current application.
- According to the entry configuration, asynchronously pull the related static resources, and finally return the template code template and execScripts used for rendering, which is used to execute the entry.js method to obtain hooks.
- Create a sandbox environment(proxy) for the current application, and execute execScripts in the sandbox environment to obtain the hook function of entry.js, and finally loadApp returns the processed hook function.
We have discussed a lot of pre-loading schemes for applications before. Considering the scale and performance impact of micro-applications to be managed in the future, we decided to adopt a pre-loading scheme. Need to manually configure which applications need to load static resources in advance, mainly let us talk about the processing and thinking behind in detail:
- Filter the applications that have been mounted, and the application resources that have been mounted must be loaded, so there is no need to preload.
- After the first application in the registered micro application is mounted, the pre-loaded other pre-loaded applications will be pre-loaded. Single-spa has done some custom events, one of which is after the first micro application is mounted. The triggered event is single-spa:first-mount. Therefore, we listen to this event, and when the first micro application is mounted, we can start pre-loading tasks.
- Use the window.requestIdleCallback API to preload application resources during the browser's idle time. In mobile devices and weak network environments, we will not start the preload task. In browsers that do not support window.requestIdleCallbackAPI, we use setTimeout to simulate.
The word "sandbox" sounds tall, but in fact we have been in touch very early. The specific concepts and details are not repeated here, you can search for yourself. Simply put, when you want to parse or execute untrusted js, when you want to isolate the execution environment of the executed code, when you want to restrict the accessible objects in the executed code, the sandbox is sent Useful.
Hijack the HTMLHeadElement.prototype.appendChild method, take over appendChild, and do style snapshot generation and recovery operations when applying mount and unmount. Later consider using the shadow dom scheme for style isolation, which is more thorough and safe.
Local cache resources can effectively reduce the loading time of resource requests, speed up application rendering, and reduce page blank time. After comparing the various local data storage solutions supported by browsing, I eventually chose IndexedDB as the solution for storing static resources. Why did I choose it? I won't go into details here. The detailed treatment has the following points:
- Use Dexie.js to manage IndexedDB database
- Set the cache period to 7 days, expired resources will be cleared
- The core APIs are cacheAssets, getCacheAssets, clearExpiredAssets
5 . Summary
To sum up, Midway's overall design concept is based on high cohesion and low coupling, adhering to the concept of micro front end, and implemented a platform service system of front-end rendering and back-end management. Users no longer need to pay attention to the technical details of application aggregation. , Ready to use out of the box.
At present, the multi-system division of the car rental business line has begun to use the Midway platform to start governance. The problem domain modules are also split according to the micro-application granularity to achieve multiple system multiplexing. Multiple access greatly reduces the system construction threshold and the repeatability of business module development. In the future, we will continue to integrate the capabilities of engineering, security monitoring, performance experience, data visualization and other directions into Midway while building on the core capabilities of Midway micro front-end. Best practices for building solutions.
The small orange car service terminal technical team under Didi Chuxing is a young, responsible, energetic, and pursuing the ultimate in technology. A large terminal technical team with multiple business lines such as Juyang. The front-end technology stacks involved include vue, react, nodejs, flutter, and WeChat applets. Currently, there are a large number of positions in Hangzhou and Beijing for a long time, including some internship positions.
Long-term recruitment positions:
- Front-end engineer
- Client engineer(Android/iOS)
- AIoT hardware engineer(priority of car linkage is preferred)
- 2021 graduates(graduation time:20.11 ~ 21.10) intern
Welcome to send your resume to:
Please name the subject of the email as "Name + Application Department + Application Direction"
We will take every delivery seriously and give the fastest processing speed!
About the Author
He graduated from Beijing University of Posts and Telecommunications and joined Didi in 2019. He likes small pets and is good at technology. Currently in car service terminal technology is responsible for car rental related work, and strive to be an ideal, life-loving program ape.
\ * \ * Welcome to pay attention to Didi Technology Public Account!
This article was published by the blog group openWrite