In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
Editor to share with you the example analysis of micro-front-end architecture, I believe that most people do not know much about it, so share this article for your reference, I hope you will learn a lot after reading this article, let's learn about it!
What is a micro-front-end
When it comes to micro-front-end, micro-services are inseparable from micro-services. Micro-services allow the back-end architecture to be extended through a loosely coupled code base, each of which is responsible for its own business logic and exposes an API. Each API can be deployed independently and is owned and maintained by different teams.
The front-end architecture has gone through the process from monomer, to front-end separation, to micro-service, and finally to the current micro-front-end, as shown in the figure below:
The idea of the micro-front-end is to introduce the micro-service architecture to the front-end, and its core is to be able to build an end-to-end vertical architecture based on the business unit, so that a single team can independently carry out related development. at the same time, it also has considerable flexibility to form the delivery application according to the demand.
The term "micro-front-end" was first coined on ThoughtWorks technology radar at the end of 2016. It extends the concept of microservices to the front-end world. The current trend is to build a powerful and powerful browser application (also known as a single-page application) that sits on top of the micro-service architecture. Over time, the front-end layer, usually developed by a separate team, grows and becomes more difficult to maintain.
The idea behind the micro front end is to think of a website or Web application as a combination of functions owned by an independent team. Each team has different business or task areas of its own concern and expertise. A team is cross-functional and develops its functionality end-to-end from the database to the user interface.
But the idea is not new. It has a lot in common with the concept of "monomer system". In the past, a similar approach was called "front-end integration of vertical systems". But micro-front-end is obviously a friendlier and lighter term.
In the micro-service architecture, the background services have been separated according to the business, while the front end is still a single construction, through the gateway to invoke different background services. The idea of this micro-service is contrary to each other, which causes your back-end team to be divided by business, but the front-end team is still a whole. Micro-front-end can effectively improve this.
The core idea of the micro-front end is actually the remote application, which includes the runtime loading of components / modules / packages.
As shown in the figure above, for users, the access is a micro-front-end container (container) that loads applications running on remote services and loads these remote applications as components / modules / packages in the local browser.
The component is the building unit of the underlying UI library
The module is the building unit of the corresponding runtime
The package is the building unit of the dependency parser
The micro-front end is the building block of the proposed application.
Second, why do you need a micro-front-end? What are its advantages?
In the previous micro-front-end architecture, all the front-end is still a single, the front-end team will rely on all services or background API, front-end development will become the bottleneck of the whole system. The use of micro-front-end is to change the front-end business from horizontal layering to vertical application, enter the business team, and divest the coupling.
So what are the benefits of micro-front-end, and why use micro-front-end architecture?
Each team develops independently, does not affect each other, develops and deploys independently, the micro-application warehouse is independent, the front and rear end can be developed independently, and the main framework automatically updates synchronously after deployment.
Incremental upgrade, in the face of a variety of complex scenarios, it is usually difficult to upgrade or reconstruct an existing system, and micro-front-end is a very good means and strategy to implement progressive reconstruction. Because it is loaded at run time, you can add, remove, or replace parts of the front end without rebuilding.
Regardless of technology, each team should be able to select and upgrade its technology stack without having to coordinate with other teams. That is to say, App A can use React, while App B can use Vue, so you can load it through the same micro-front end.
When running independently, the state of each micro-application is isolated, and the runtime state is not shared. Isolate team code, even if all teams use the same framework, do not share the runtime. Build self-contained stand-alone applications. Do not rely on shared state or global variables.
Establish team namespaces that avoid conflicts and clarify ownership for CSS, events, local storage, and Cookies.
Therefore, the essence of micro-front-end and micro-services is about decoupling. It is only when the application reaches a certain size that it begins to make more sense.
Third, how to realize the micro-front-end architecture
Micro-front end is not a library, but a design idea of front-end architecture. in essence, the realization of micro-front-end is to load applications remotely at run time.
There are several ways to realize a micro-front-end. From a construction point of view, there are two ways: build a micro-front-end at compile time and build a micro-front-end at run time:
The compile-time micro-front-end usually uses components in third-party libraries as packages and introduces dependencies at build time. The introduction of a new micro-front end into this implementation requires recompilation and is not flexible enough. The micro-front end at compile time can be realized by means of Web Components,Monorepo and so on. Among them, Monorepo is very popular, and common tools are nx,rush,lerna and so on.
A runtime micro-front-end is when a micro-front-end is dynamically injected into a container application at a time or on demand through delayed loading. When a new micro-front end is introduced, there is no need to build, and loading can be defined dynamically in the code. In my eyes, micro-front end refers more to this kind of run-time loaded micro-front-end, because independent build, deployment and testing is our definition of "micro".
From the perspective of front-end responsibility layering, it can be realized from the front-end or back-end.
Implemented through the client framework
Micro-front-end is usually supported by client-side tools (which sounds reasonable). There are many implementation tools that support client-side development of micro-front-end, including: Piral,Open Components,qiankun,Luigi,Frint.js and so on. Qiankun was developed by Ant Financial Services Group.
On the client side, it can also be implemented by auxiliary libraries, which can provide some infrastructure for shared dependencies, routing events, or different micro-front ends and their lifecycles.
The following example handles shared dependencies through mechanisms such as importing maps or packaging specific blocks.
Related tools include Webpack5 Module Federation,Siteless,Single SPA,Postal.js and so on.
Through the server-side implementation
Micro-front-end can not only be implemented on the client side, similar to server-side rendering, but also can be implemented through the server side.
The supporting tools of server-side micro-front end are: Mosaic,PuzzleJs,Podium,Micromono and so on.
Well, after saying so much, I believe you look confused. How on earth did it come true? Let's put aside the architecture and see how it works.
Fourth, the specific implementation of the runtime micro-front-end Iframe
Iframes is that you can embed another HTML in html. Here is an example of implementing a micro-front end with iframe:
Your browser does not support iframes.
Your browser does not support iframes.
Without considering the problem of experience, iframe is almost the perfect micro-front-end solution. Iframe provides native isolation solutions for browsers, and problems such as style isolation and js isolation can be solved perfectly. But its biggest problem is that its isolation can not be broken, resulting in the context between applications can not be shared, resulting in the problems of development experience and product experience. The main problems here include:
Url is out of sync. The browser refresh iframe url status is missing and the back forward button cannot be used.
UI is out of sync and DOM structure is not shared.
The global context is completely isolated and memory variables are not shared.
Slow. Each sub-application entry requires secondary browser context reconstruction and resource reloading.
So although you can use iframe to achieve the effect of remote loading, because of these limitations, few applications will use it.
Nginx routing
Using Ngix routing, we can route different requests to different micro-front-end applications.
For example, the routing capability of Nginx can dynamically request different back-end applications at the front end, while each back-end application runs independently, and the front end can load these different back-end applications and orchestrate them together. The following code is a configuration of Nginx. Customers/users/admins represents three different applications, and the front end loads the back-end applications on different services through routing.
Worker_processes 4; events {worker_connections 1024;} http {server {listen 80; root / usr/share/nginx/html; include / etc/nginx/mime.types; location / app1 {try_files $uri app1/index.html;} location / app2 {try_files $uri app2/index.html } location / app3 {try_files $uri app3/index.html;}
No matter what kind of micro-front-end architecture you use, Nginx direction proxy or other API gateway solutions can provide convenient and flexible back-end routing functions. However, in this way, it is necessary to define a general scalable routing rule, otherwise, when introducing new applications, it is very inconvenient to modify the routing configuration of Nginx.
Webpack 5 Module Federation
Webpack5's Module Federation is an exciting innovation that can easily support the construction of micro-front ends. Module syndication allows JavaScript applications to dynamically load code from another application and share dependencies in the process. If the application that uses Module Federation does not have the dependencies required by the federated code, Webpack downloads the missing dependencies from the federated build source.
In the context of Module Federation, startup code is an enforcement strategy for attaching runtime code to the remote container startup sequence. This is really useful because you can't access ModuleFederation and its runtime through Hook, and you can't extend it or add a line of code that can operate like a public path to a remote container dynamically. This is trivial in a normal webpack application, but it is difficult to do so in an inaccessible custom runtime container that powers module federation with remote orchestration. To put it simply, Module Federation injects a piece of runtime code to load and orchestrate remote application code, and is able to manage and load remote application dependencies.
Here is an example of this:
Module.exports = {mode: 'development', devServer: {port: 8080,}, plugins: [new ModuleFederationPlugin ({name:' container', remotes: {microFrontEnd1: 'microFrontEnd1@ http://localhost:8081/remoteEntry.js', microFrontEnd2:' microFrontEnd2@ http://localhost:8082/remoteEntry.js',} })]}
The above code is the configuration of the container side of the micro-front end, and the container is responsible for loading the code of other remote applications. In this example, it loads two remote applications.
Module.exports = {mode: 'development', devServer: {port: 8081,}, plugins: [new ModuleFederationPlugin ({name:' microFrontEnd1', filename: 'remoteEntry.js', exposes: {'. / MicroFrontEnd1Index':'. / src/index',},}) ]}
The Webpack configuration for each micro-front end is as above.
ModuleFederationPlugin,remote can be used to load remote applications, while Expose can expose its components as remote components.
In container, you only need to call the following code to load the remote component.
Import 'microFrontEnd1/MicroFrontEnd1Index'; import' microFrontEnd2/MicroFrontEnd2Index'
The loading process of Module Federation is shown in the figure above:
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
Localhost loads index.html
Main.js is the core orchestration code of Module Federation and is responsible for loading remote components.
RemoteEntry.js is the code of the remote component exposed by Module Federation
Src_ is the packaged code, where bootstrap_js is the container side code and index_js is the micro front side code.
Module Federation implements the ability to load remote code at run time, similar to dynamic link libraries. Remote code is essentially a global variable loaded on window, and Module Federation can help solve the problem of dependency. As an ancient language, Javascrip does not provide dependency management, which leaves room for all kinds of gods to play.
The disadvantage of Module Federation is that it relies on Webpack 5, and packages are mounted directly as global variables.
EMP micro-front-end is a micro-front-end solution based on Module Federation.
Single SPA
Single-page application is the mainstream of Web application nowadays, which is different from the traditional multi-page application. The whole SPA has only one page, and its content is loaded through the function of Javascript.
SPA is a Web application that contains only one HTML page. Provides dynamic updates that allow you to interact with the page without refreshing it. With a single-page application you can significantly reduce server load and increase load speed resulting in a better user experience because SPA imports data on demand only when the entire page was previously loaded.
In addition to the complexity of development, it is not friendly to SEO, but the biggest technical disadvantage of page applications is that URL is not suitable for sharing, because SPA has only one address.
Single-spa is a framework for combining multiple JavaScript micro-fronts in front-end applications.
Using single-spa to build a front end can bring many benefits, such as:
Use multiple frames on the same page without refreshing the page (React,AngularJS,Angular,Embe)
Independent deployment of micro-front end
Write code using the new framework without having to rewrite existing applications
Delayed loading code shortens initial loading time
The single-spa application consists of the following:
The single-spa root configuration, which is used to render the HTML page and the JavaScript of the registered application. Each application registers the following three items: name, the function that loads the application code, and the function that determines when the application is active / inactive
An application that is packaged into a single-page application. Each application must know how to boot, install, and uninstall itself from DOM. The main difference between traditional SPA and Single-SPA applications is that they must be able to coexist with other applications because they each do not have their own HTML pages. For example, a React or Angular SPA application. When active, they can listen for url routing events and put the content on the DOM. When inactive, they do not listen for url routing events and have been completely removed from DOM.
An application registered with Single-SPA has all the features of a normal SPA, except that it does not have a HTML page. SPA contains many registered applications, each with its own framework. Registered applications have their own client routing and their own framework / library. They present their own HTML and are completely free to do whatever they want at installation time. The concept of mounting refers to whether the registered application is putting content on the DOM. It is its activity feature that determines whether to mount a registered application. Whenever a registered application is not mounted, it should remain fully dormant until it is mounted.
The sample code for Single SPA is as follows:
1. Micro front end code: import React from "react"; import ReactDOM from "react-dom"; import singleSpaReact from "single-spa-react"; import Root from ". / root.component"; const lifecycles = singleSpaReact ({React, ReactDOM, rootComponent: Root, errorBoundary (err, info, props) {/ / Customize the root error boundary for your microfrontend here. Return null;},}); export const {bootstrap, mount, unmount} = lifecycles
The micro-front end of Single SPA is a pure JS component that does not contain HTML and needs to be loaded through a container.
two。 Root Config of the container
On the container side, you need to define remote components and register remote applications through Import Map or Webpack.
{"imports": {"@ naughty/root-config": "/ / localhost:9000/naughty-root-config.js", "@ naughty/app": "/ / localhost:8500/naughty-app.js", "react": "https://cdn.jsdelivr.net/npm/react@16.13.1/umd/react.production.min.js"," "react-dom": "https://cdn.jsdelivr.net/npm/react-dom@16.13.1/umd/react-dom.production.min.js"}}
The HTML file on the container side uses import map to define remote dependencies, where root-config is orchestrated code and is responsible for registering and loading remote applications. All shared dependencies need to be defined at the same time. Here are react and react-dom.
Import {registerApplication, start} from "single-spa"; registerApplication ({name: "@ single-spa/welcome", app: () = > System.import ("https://unpkg.com/single-spa-welcome/dist/single-spa-welcome.js"), activeWhen: [" / welcome "],}) RegisterApplication ('@ naughty/app', () = > System.import ('@ naughty/app'), location = > location.pathname.startsWith ('/ app')); start ({urlRerouteOnly: true,})
In root-config, we registered two remote applications that were loaded using different url. / welcome will load the welcome application, and / app will load our app application.
The core of Single SPA is to load remote components using different URL routes, which can work with Webpack (build dependencies at packaging time) or Import Map (import dependencies at runtime using browsers). Be careful not to mix the two dependency mechanisms in your micro-front end.
Single SPA also provides a layout engine that can help you quickly build a micro-front end.
Compared to Module Federation,Single SPA's code and lifecycle management, it provides a clear interface, but the disadvantage is that shared dependencies need to be managed manually through import map.
It is not easy to make a good micro-front end because it is limited by some features of the browser and JS. In addition to the content we share today, we are also faced with many challenges: how to solve the conflict of css/js to make components and applications completely isolated; how to solve the communication between different applications; how to deal with routing; how to ensure the unity of UI style and so on.
V. problems and shortcomings of micro-front-end
After talking about so many advantages and implementations, is the micro-front end a silver bullet to solve the front-end development problem? Of course not. All architectures are trade-offs and trade-offs, there is no silver bullet in this world, micro-front-end architecture and micro-services also have their drawbacks, single architecture is not necessarily poor.
1. The construction of micro-front end is usually more complex, from tools, packaging, to deployment, micro-front end is more complex, there is no free lunch, for small projects, its cost is too high.
two。 Each team can use a different framework, which sounds beautiful, but in practice, it doesn't make much sense except to support applications left over from history. At the same time, it also brings problems in experience. It is one thing to be able to load different framework code remotely, another to make good use of them all.
3. From a performance point of view, there may be problems if the performance of the micro-front-end is not well optimized, at least the micro-front-end framework is an additional layer of loading. If different micro-front ends use different frameworks, then each framework requires additional loading.
Micro-front-end architecture is still in development, iframe/nginx/module federation/single-spa mentioned in this article is only a small part of many solutions, front-end development and ecosystem is really rich, other solutions such as umd/, Piral,open comonent and so on. When using, you can also choose standard Web Component or ES Modules to build micro-front end, but these standard browser support is not very good, this is the pain of front-end development forever.
The above is all the content of this article "sample Analysis of Micro-front-end Architecture". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.