第13到22行包含要啟動(dòng)微型前端的代碼。通常,微前端之間沒(méi)有通信,并且容器與微前端之間的通信有限。
通常,它是從容器到微前端的一種方式。在這里,第34行通過(guò)ContainerID和歷史,因?yàn)樗奈⑶岸舜尸F(xiàn)如下:
ReactDOM.render(<App history={history} />, document.getElementById(containerId));
第18行將腳本的Crondorigin值設(shè)置為空,這相當(dāng)于匿名。這意味著元素的請(qǐng)求將使其模式設(shè)置為CORS及其憑據(jù)模式設(shè)置為相同原點(diǎn)。
我們?cè)趯?shí)際代碼中修改了Came的示例。無(wú)論如何,這是我們使用的基礎(chǔ)?;诖?,我們可以向您展示如何將應(yīng)用程序轉(zhuǎn)換為微前端。
5個(gè)步驟將隨機(jī)反應(yīng)應(yīng)用程序轉(zhuǎn)換為微前端
我們?yōu)殡S機(jī)反應(yīng)應(yīng)用程序的選擇是創(chuàng)建React應(yīng)用程序。將其變成微前端需要五個(gè)步驟。
關(guān)于Facebook的皇冠珠寶應(yīng)用程序的許多原則都在創(chuàng)建React應(yīng)用程序的10個(gè)有趣的事實(shí)中描述。在本文中,我們強(qiáng)調(diào)應(yīng)用這些原則。
第1步:修改package.json以設(shè)置端口并使用“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" ] } }
在第12行中,添加react-app-rewired作為依賴項(xiàng),這允許在不彈出它的情況下自定義應(yīng)用程序。
在第15行中,應(yīng)用程序的啟動(dòng)端口已從默認(rèn)端口3000更改為所選的4000 - 這避免了由于容器本身在端口3000上運(yùn)行以來(lái)端口沖突。
從15號(hào)線到第17行,反應(yīng)腳本由Reft-App-Rewifired替換。
使用新端口,創(chuàng)建React應(yīng)用程序顯示UI如下所示。(我們欺騙了一點(diǎn)。使用React-App-Rewired需要在應(yīng)用程序運(yùn)行之前更改步驟2。)
步驟2:使用config-overrides.js禁用代碼拆分
默認(rèn)情況下,啟用代碼拆分。應(yīng)用程序分為多個(gè)可以獨(dú)立加載到頁(yè)面上的塊。
http:// localhost:4000 / asset-manifest.json 顯然顯示該應(yīng)用程序已被捆綁。
此加載優(yōu)化會(huì)導(dǎo)致掛載和卸載Micro Front-Ender的問(wèn)題。我們需要通過(guò)創(chuàng)建或編輯config-overrides.js來(lái)禁用塊,如下所示:
module.exports = { webpack: (config, env) => { config.optimization.runtimeChunk = false; config.optimization.splitChunks = { cacheGroups: { default: false, }, }; return config; }, };
之后,http:// localhost:4000 / asset-manifest.json顯示沒(méi)有塊。
如果未從Create React應(yīng)用程序生成React應(yīng)用程序,則可以通過(guò)修改WebPack配置來(lái)完成步驟1和步驟2。
如果使用我們的改進(jìn)的MicroFrontend.js,則不必在步驟1中使用React-App-Rewifirew,并且可以完全跳過(guò)步驟2。5步減少到3.5。詳細(xì)信息描述于“您不必對(duì)微前端丟失優(yōu)化”中。
此保存在此回購(gòu)的ChunkOptimization分支中捕獲。
第3步:在SRC / index.js中進(jìn)行更改以定義渲染和卸載功能
讓我們來(lái)看看瀏覽Micro前端的SRC / index.js:
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( <App history={history} />, document.getElementById(containerId), ); unregister(); }; window.unmountBrowse = containerId => { ReactDOM.unmountComponentAtNode(document.getElementById(containerId)); };
window.RenderBrowse和window.unmountBrowse定義。這些方法由容器的Microfrontend.js調(diào)用。需要為Create React應(yīng)用程序的SRC / index.js 定義類似的方法。
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( <App history={history}/>, 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(<App />, 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();
從第7行到第19行,窗口.RenderCreateActApp和Window.unmountCreaterActApp正在添加。
第23線變?yōu)闂l件。如果它是一個(gè)獨(dú)立的應(yīng)用程序,它將被呈現(xiàn)為根元素。如果它是一個(gè)微型前端,它將通過(guò)window.rendercreateActapp呈現(xiàn)給ContainID。
第4步:使用src / setupproxy.js設(shè)置CORS規(guī)則
在Web瀏覽器中啟動(dòng)Micro前端時(shí),我們獲得了CORS錯(cuò)誤:
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.
必須通過(guò)創(chuàng)建或編輯src / setupproxy.js來(lái)設(shè)置以下代理。
module.exports = app => { app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', '*'); next(); }); };
在進(jìn)行第5步之前,我們?yōu)槿萜髯隽艘恍╊~外的工作。
在.env文件中,需要添加新的Host
React_App_CreateActApp_Host。端口4000需要匹配創(chuàng)建React App正在運(yùn)行的Real Port。
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
需要對(duì).env.生產(chǎn)需要做類似的變化:
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
在App Header.is中添加導(dǎo)航鏈接,以使UI可訪問(wèn)。這是可選的。
import React from 'react'; import { NavLink } from 'react-router-dom'; import './AppHeader.css'; const AppHeader = () => ( <header> <div className="center-column"> <h2> Feed me</h2> </div> <nav> <ol className="center-column"> <li> <NavLink to="/">Browse restaurants</NavLink> </li> <li> <NavLink to="/random">Surprise me</NavLink> </li> <li> <NavLink to="/createreactapp">Create React App</NavLink> </li> <li> <NavLink to="/about">About</NavLink> </li> </ol> </nav> </header> ); export default AppHeader;
將CreateAteActApp及其路由添加到Container的App.js中:
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 }) => ( <MicroFrontend history={history} host={browseHost} name="Browse" /> ); const Restaurant = ({ history }) => ( <MicroFrontend history={history} host={restaurantHost} name="Restaurant" /> ); const Createreactapp = ({ history }) => ( <MicroFrontend history={history} host={createreactappHost} name="Createreactapp" /> ); const Random = () => <Redirect to={`/restaurant/${getRandomRestaurantId()}`} />; const App = () => ( <BrowserRouter> <React.Fragment> <AppHeader /> <Switch> <Route exact path="/" component={Browse} /> <Route exact path="/restaurant/:id" component={Restaurant} /> <Route exact path="/createreactapp" component={Createreactapp} /> <Route exact path="/random" render={Random} /> <Route exact path="/about" render={About} /> </Switch> </React.Fragment> </BrowserRouter> ); export default App;
現(xiàn)在讓我們?cè)囍故疚覀兊奈⑿颓岸恕?/p>
內(nèi)容服務(wù)器:NPM啟動(dòng)。
瀏覽Micro前端:NPM開(kāi)始。
餐廳訂購(gòu)微型前端:NPM開(kāi)始。
Create React App Micro前端:NPM開(kāi)始。
容器:NPM開(kāi)始。
轉(zhuǎn)到localhost:3000 / createActapp來(lái)啟動(dòng)頁(yè)面。
哎呀,React spinning 日志在哪里?
讓我們重新審視http:// localhost:4000 / asset-manifest.json。Micro前端的徽標(biāo)是一個(gè)單獨(dú)的文件:
{ "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" ] }
我們忘了抓住它!
查看此徽標(biāo)SVG文件的來(lái)源,該文件被設(shè)置為/static/media/logo.5d5d9eef.svg。此文件可在Create React App(HTTPS:// localhost:4000)中使用,但不在容器中(http:// localhost:3000)。
這是我們的最后一步。
步驟5:在.env文件中配置內(nèi)容主機(jī)并將其用來(lái)前綴靜態(tài)內(nèi)容
創(chuàng)建或編輯.env以設(shè)置內(nèi)容主機(jī):
REACT_APP_CONTENT_HOST=http://localhost:4000
當(dāng)Micro前端使用靜態(tài)內(nèi)容時(shí),它需要在HTML中的%React_App_Content_host%前綴,并在JavaScript中的
Process.env.reacect_app_content_host。
在這里,我們?cè)趕rc / app.js中更改了第9行:
import React from 'react'; import logo from './logo.svg'; import './App.css'; function App() { return ( <div className="App"> <header className="App-header"> <img src={`${process.env.REACT_APP_CONTENT_HOST}${logo}`} className="App-logo" alt="logo" /> <p> Edit <code>src/App.js</code> and save to reload. </p> <a className="App-link" href="https://reactjs.org" target="_blank" rel="noopener noreferrer" > Learn React </a> </header> </div> ); } export default App;
使用此更改,徽標(biāo)SVG文件以http:// localhost:4000前綴。
該應(yīng)用程序現(xiàn)在正常工作。