In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
Today, I will talk to you about how to convert random React applications into micro-front-ends, which may not be well understood by many people. In order to make you understand better, the editor has summarized the following contents for you. I hope you can get something from this article.
What is the micro-front-end method? The micro-front-end term was first proposed in the November 2016 thought technology radar. It extends the concept of micro-services to front-end development.
This method divides the browser-based code into micro-front-end by decomposing the application function. By making a small and feature-centric CodeBases, we achieve the goal of decoupling software development.
Although Codebases has been decoupled, the user experience is coherent. In addition, each code base can be implemented, upgraded, updated, and deployed independently.
This is the paradise of micro-front end. Regardless of the framework and version, the javascript application is started by the container. These applications, legacy and new, work together seamlessly and are similar to one application.
In our example, we will address the case of a simpler React micro-front end.
Working on the future of building a miniature front-end container that initiates React applications
This container needs to have the ability to launch a random response application without knowing many details. In addition, due to the concept of micro-front end, this layer needs to be very thin, with little business logic.
Fortunately, Cam Jackson announced his micro front-end work for us to adopt. His job is available at this location:
Containers: entry points and container applications for micro-front-end demonstrations.
A miniature front end for browsing restaurants: browsing.
The miniature front end of ordering food from the restaurant: restaurant ordering.
Content server: where static content is stored in the micro-front-end presentation.
This is how the micro-front end works:
Start the content server.
Launch the browsing and restaurant ordering application on a specific port.
Based on URL, the container will route to one of the miniature front ends.
The selected Micro front end goes to a specific port to get the application's asset list. JSON. From this JSON file, the included main.js is tagged and loaded in the script.
The manifest file contains a mapping of all asset file names for its corresponding output file so that it can be selected without parsing the index.html. The core of the container is the following Microfrontend.js:
Import React from 'react'; class MicroFrontend extends React.Component {componentDidMount () {const {name, host, document} = this.props; const scriptId = `micro-frontend-script-$ {name} `; if (document.getElementById (scriptId)) {this.renderMicroFrontend (); return } fetch (`${host} / asset- room.json`) .then (res = > res.json ()) .then (manifest = > {const script = document.createElement ('script'); script.id = scriptId; script.crossOrigin =''; script.src = `$ {host} ${manifest ['main.js']}`; script.onload = this.renderMicroFrontend; document.head.appendChild (script) });} componentWillUnmount () {const {name, window} = this.props; window [`unmount$ {name}`] (`${name}-container`);} renderMicroFrontend = () = > {const {name, window, history} = this.props; window [`render$ {name}`] (`$ {name}-container`, history);}; render () {return }} MicroFrontend.defaultProps = {document, window,}; export default MicroFrontend
Lines 13 to 22 contain the code to start the mini-front end. In general, there is no communication between the micro front end, and the communication between the container and the micro front end is limited.
Typically, it is a way from the container to the micro-front end. Here, line 34 passes through ContainerID and history, because its micro front end is to be rendered as follows:
ReactDOM.render (, document.getElementById (containerId))
Line 18 sets the Crondication value of the script to null, which is equivalent to anonymity. This means that the request for the element will set its mode to CORS and its credential mode to the same origin.
We modified the example of Came in the actual code. In any case, this is the basis for our use. Based on this, we can show you how to convert an application to a micro-front end.
5 steps to convert a random response application to a micro-front-end
Our choice for random response applications is to create React applications. It takes five steps to turn it into a micro-front end.
Many of the principles about Facebook's Crown Jewelry application are described in 10 interesting facts about creating a React application. In this article, we emphasize the application of these principles.
Step 1: modify package.json to set the port and use "React-App-Rewifire" {"name": "my-app", "version": "0.1.0", "private": true, "dependencies": {"@ testing-library/jest-dom": "^ 4.2.4", "@ testing-library/react": "^ 9.4.0" "@ testing-library/user-event": "^ 7.2.1", "react": "^ 16.12.0", "react-dom": "^ 16.12.0", "react-scripts": "3.4.0", "react-app-rewired": "2.1.5"}, "scripts": {"start": "PORT=4000 react-app-rewired start" "build": "react-app-rewired build", "test": "react-app-rewired test", "eject": "react-scripts eject"}, "eslintConfig": {"extends": "react-app"}, "browserslist": {"production": ["> 0.2%", "not dead", "not op_mini all"] "development": ["last 1 chrome version", "last 1 firefox version", "last 1 safari version"]}}
In line 12, add react-app-rewired as a dependency, which allows you to customize the application without popping it up.
In line 15, the startup port of the application has been changed from the default port 3000 to the selected 4000-this avoids port conflicts since the container itself is running on port 3000.
From line 15 to line 17, the response script is replaced by Reft-App-Rewifired.
Using the new port, create a React application that displays the UI as shown below. We cheated a little. Using React-App-Rewired requires changing step 2 before the application runs.)
Step 2: disable code splitting using config-overrides.js
Code splitting is enabled by default. The application is divided into blocks that can be loaded onto the page independently.
Http:// localhost:4000 / asset-manifest.json clearly shows that the application is bundled.
This load optimization can cause problems with mounting and unloading Micro Front-Ender. We need to disable the block by creating or editing the config-overrides.js, as follows:
Module.exports = {webpack: (config, env) = > {config.optimization.runtimeChunk = false; config.optimization.splitChunks = {cacheGroups: {default: false,},}; return config;},}
After that, http:// localhost:4000 / asset-manifest.json shows no blocks.
If the React application is not generated from the Create React application, you can complete steps 1 and 2 by modifying the WebPack configuration.
If you use our improved MicroFrontend.js, you don't have to use React-App-Rewifirew in step 1, and you can skip step 2 completely. 5 steps reduced to 3.5. The details are described in "you don't have to optimize the micro-front end."
This save is captured in the ChunkOptimization branch of this buyback.
Step 3: make changes in SRC / index.js to define rendering and unloading capabilities
Let's take a look at SRC / index.js at the front end of Micro:
Import 'react-app-polyfill/ie11'; import React from' react'; import ReactDOM from 'react-dom'; import App from'. / App'; import {unregister} from'. / registerServiceWorker'; window.renderBrowse = (containerId, history) = > {ReactDOM.render (, document.getElementById (containerId),); unregister ();}; window.unmountBrowse = containerId = > {ReactDOM.unmountComponentAtNode (document.getElementById (containerId));}
Window.RenderBrowse and window.unmountBrowse definitions. These methods are called by the container's Microfrontend.js. You need to define a similar method for the SRC / index.js of the Create React application.
Import React from 'react'; import ReactDOM from' react-dom'; import'. / index.css'; import App from'. / App'; import * as serviceWorker from'. / serviceWorker'; / / render micro frontend function window.renderCreatereactapp = (containerId, history) = > {ReactDOM.render (, document.getElementById (containerId)); serviceWorker.unregister ();}; / / unmount micro frontend function window.unmountCreatereactapp = containerId = > {ReactDOM.unmountComponentAtNode (document.getElementById (containerId));} / / Mount to root if it is not a micro frontend if (! document.getElementById ('Createreactapp-container')) {ReactDOM.render (, document.getElementById (' root'));} / / If you want your app to work offline and load faster, you can change / / unregister () to register () below. Note this comes with some pitfalls. / / Learn more about service workers: https://bit.ly/CRA-PWA serviceWorker.unregister ()
From lines 7 to 19, the window .RenderCreateActApp and Window.unmountCreaterActApp are being added.
Line 23 becomes a condition. If it is a stand-alone application, it will be rendered as the root element. If it is a miniature front end, it will be presented to ContainID via window.rendercreateActapp.
Step 4: use src / setupproxy.js to set CORS rules
When we launch the Micro front end in a Web browser, we get a CORS error:
Access to fetch at 'http://localhost:4000/asset-manifest.json' from origin' http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
The following proxies must be set by creating or editing src / setupproxy.js.
Module.exports = app = > {app.use ((req, res, next) = > {res.header ('Access-Control-Allow-Origin',' *'); next ();});}
Before moving on to step 5, we did some extra work for the container.
In the .env file, you need to add a new Host
React_App_CreateActApp_Host . Port 4000 needs to match the Real Port that the creation React App is running.
REACT_APP_BROWSE_HOST= http://localhost:3001 REACT_APP_RESTAURANT_HOST= http://localhost:3002 REACT_APP_CREATEREACTAPP_HOST= http://localhost:4000 REACT_APP_CONTENT_HOST= http://localhost:5000
It is necessary to. Env. Production needs to make similar changes:
REACT_APP_BROWSE_HOST= https://browse.demo.microfrontends.com REACT_APP_RESTAURANT_HOST= https://order.demo.microfrontends.com REACT_APP_CREATEREACTAPP_HOST= https://createreactapp.demo.microfrontends.com REACT_APP_CONTENT_HOST= https://content.demo.microfrontends.com
Add navigation links in App Header.is to make UI accessible. This is optional.
Import React from 'react'; import {NavLink} from' react-router-dom'; import'. / AppHeader.css'; const AppHeader = () = > (Feed me Browse restaurants Surprise me Create React App About) Export default AppHeader
Add CreateAteActApp and its routes to the App.js of Container:
Import React from 'react'; import {BrowserRouter, Switch, Route, Redirect} from' react-router-dom'; import AppHeader from'. / AppHeader'; import MicroFrontend from'. / MicroFrontend'; import About from'. / About'; const {REACT_APP_BROWSE_HOST: browseHost, REACT_APP_RESTAURANT_HOST: restaurantHost, REACT_APP_CREATEREACTAPP_HOST: createreactappHost,} = process.env; let numRestaurants = 0 Fetch (`${process.env.REACT_APP_CONTENT_HOST} / restaurants.json`) .then (res = > res.json ()) .then (restaurants = > {numRestaurants = restaurants.length;}); const getRandomRestaurantId = () = > Math.floor (Math.random () * numRestaurants) + 1; const Browse = ({history}) = > (); const Restaurant = ({history}) = > (); const Createreactapp = ({history}) = > (); const Random = () = > () Const App = () > (); export default App
Now let's try to show our miniature front end.
Content server: NPM starts.
Browse the front end of Micro: start with NPM.
Restaurant order miniature front end: NPM start.
Create React App Micro front end: start with NPM.
Container: start with NPM.
Go to localhost:3000 / createActapp to launch the page.
Gee, where is the React spinning log?
Let's re-examine http:// localhost:4000 / asset-manifest.json. The logo on the front end of the Micro is a separate file:
{"files": {"main.js": "/ static/js/bundle.js", "main.js.map": "/ static/js/bundle.js.map", "index.html": "/ index.html", "static/media/logo.svg": "/ static/media/logo.5d5d9eef.svg"}, "entrypoints": ["static/js/bundle.js"]}
We forgot to catch it!
View the source of this logo SVG file, which is set to / static/media/logo.5d5d9eef.svg. This file can be used in Create React App (HTTPS:// localhost:4000), but not in a container (http:// localhost:3000).
This is our last step.
Step 5: configure the content host in the .env file and use it to prefix static content
Create or edit .env to set up the content host:
REACT_APP_CONTENT_HOST= http://localhost:4000
When the Micro front end uses static content, it requires the% React_App_Content_host% prefix in HTML and the
Process.env.reacect_app_content_host .
Here, we changed line 9 in src / app.js:
Import React from 'react'; import logo from'. / logo.svg'; import'. / App.css'; function App () {return (
Edit src/App.js and save to reload.
Learn React);} export default App
With this change, the logo SVG file is prefixed with http:// localhost:4000.
The application is now working properly.
After reading the above, do you have any further understanding of how to convert a random React application into a micro-front end? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.
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.