5个步骤将随机React应用程序转换为微前端

开发 前端
我们在实际代码中修改了Came的示例。无论如何,这是我们使用的基础。基于此,我们可以向您展示如何将应用程序转换为微前端。

什么是微型前端方法?微前端术语首先在2016年11月的思想技术雷达中提出来。它将微服务的概念扩展到前端开发。

该方法是通过分解应用功能来将基于浏览器的代码拆分为微前端。通过制作较小且特征为中心的CodeBases,我们实现了解耦的软件开发目标。

虽然Codebases已经解耦,但用户体验是连贯的。此外,每个代码库都可以独立实现,升级,更新和部署。

这是微前端的天堂。无论框架和版本如何,javascript应用程序都由容器启动。这些应用程序,遗留和新的,无缝地一起工作,并类似于一个应用程序。

在我们的示例中,我们将解决更简单的React微型前端的情况。

在建立发起React应用程序的微型前端容器的前程工作

此容器需要具有启动随机反应应用程序的能力,而不知道许多细节。此外,由于微前端的概念,这层需要很薄,商业逻辑很少。

幸运的是,Cam Jackson公布了他的微观前端工作,让我们采用。他的工作在这个地点可以获得:

  • 容器:微前端演示的入口点和容器应用。
  • 用于浏览餐馆的微型前端:浏览。
  • 从餐厅订购食物的微型前端:餐厅订购。
  • 内容服务器:将静态内容存储微前端演示的位置。

这是微型前端工作的工作流程:

  • 启动内容服务器。
  • 在特定端口启动浏览和餐厅订购应用程序。
  • 基于URL,容器将路线到其中一个微型前端。
  • 所选的Micro前端转到特定端口以获取应用程序的资产清单.JSON。从此JSON文件中,包含的main.js置于脚本标记并加载。

清单文件包含对其相应的输出文件的所有资产文件名的映射,以便在不必解析index.html的情况下可以选择它。该容器的核心是以下Microfrontend.js:

  1. import React from 'react'; 
  2.  
  3. class MicroFrontend extends React.Component { 
  4.   componentDidMount() { 
  5.     const { name, host, document } = this.props; 
  6.     const scriptId = `micro-frontend-script-${name}`; 
  7.  
  8.     if (document.getElementById(scriptId)) { 
  9.       this.renderMicroFrontend(); 
  10.       return; 
  11.     } 
  12.  
  13.     fetch(`${host}/asset-manifest.json`) 
  14.       .then(res => res.json()) 
  15.       .then(manifest => { 
  16.         const script = document.createElement('script'); 
  17.         script.id = scriptId
  18.         script.crossOrigin = ''
  19.         script.src = `${host}${manifest['main.js']}`; 
  20.         script.onload = this.renderMicroFrontend; 
  21.         document.head.appendChild(script); 
  22.       }); 
  23.   } 
  24.  
  25.   componentWillUnmount() { 
  26.     const { name, window } = this.props; 
  27.  
  28.     window[`unmount${name}`](`${name}-container`); 
  29.   } 
  30.  
  31.   renderMicroFrontend = () => { 
  32.     const { name, window, history } = this.props; 
  33.  
  34.     window[`render${name}`](`${name}-container`, history); 
  35.   }; 
  36.  
  37.   render() { 
  38.     return <main id={`${this.props.name}-container`} />
  39.   } 
  40.  
  41. MicroFrontend.defaultProps = { 
  42.   document, 
  43.   window, 
  44. }; 
  45.  
  46. export default MicroFrontend; 

 

第13到22行包含要启动微型前端的代码。通常,微前端之间没有通信,并且容器与微前端之间的通信有限。

通常,它是从容器到微前端的一种方式。在这里,第34行通过ContainerID和历史,因为它的微前端待呈现如下:

  1. ReactDOM.render(<App history={history} />,  
  2.     document.getElementById(containerId)); 

第18行将脚本的Crondorigin值设置为空,这相当于匿名。这意味着元素的请求将使其模式设置为CORS及其凭据模式设置为相同原点。

我们在实际代码中修改了Came的示例。无论如何,这是我们使用的基础。基于此,我们可以向您展示如何将应用程序转换为微前端。

5个步骤将随机反应应用程序转换为微前端

我们为随机反应应用程序的选择是创建React应用程序。将其变成微前端需要五个步骤。

关于Facebook的皇冠珠宝应用程序的许多原则都在创建React应用程序的10个有趣的事实中描述。在本文中,我们强调应用这些原则。

第1步:修改package.json以设置端口并使用“React-App-Rewifire”

  1.   "name": "my-app", 
  2.   "version": "0.1.0", 
  3.   "private": true, 
  4.   "dependencies": { 
  5.     "@testing-library/jest-dom": "^4.2.4", 
  6.     "@testing-library/react": "^9.4.0", 
  7.     "@testing-library/user-event": "^7.2.1", 
  8.     "react": "^16.12.0", 
  9.     "react-dom": "^16.12.0", 
  10.     "react-scripts": "3.4.0", 
  11.     "react-app-rewired": "2.1.5" 
  12.   }, 
  13.   "scripts": { 
  14.     "start": "PORT=4000 react-app-rewired start", 
  15.     "build": "react-app-rewired build", 
  16.     "test": "react-app-rewired test", 
  17.     "eject": "react-scripts eject" 
  18.   }, 
  19.   "eslintConfig": { 
  20.     "extends": "react-app" 
  21.   }, 
  22.   "browserslist": { 
  23.     "production": [ 
  24.       ">0.2%", 
  25.       "not dead", 
  26.       "not op_mini all" 
  27.     ], 
  28.     "development": [ 
  29.       "last 1 chrome version", 
  30.       "last 1 firefox version", 
  31.       "last 1 safari version" 
  32.     ] 
  33.   } 
  • 在第12行中,添加react-app-rewired作为依赖项,这允许在不弹出它的情况下自定义应用程序。
  • 在第15行中,应用程序的启动端口已从默认端口3000更改为所选的4000 - 这避免了由于容器本身在端口3000上运行以来端口冲突。
  • 从15号线到第17行,反应脚本由Reft-App-Rewifired替换。

使用新端口,创建React应用程序显示UI如下所示。(我们欺骗了一点。使用React-App-Rewired需要在应用程序运行之前更改步骤2。)

步骤2:使用config-overrides.js禁用代码拆分

默认情况下,启用代码拆分。应用程序分为多个可以独立加载到页面上的块。

http:// localhost:4000 / asset-manifest.json 显然显示该应用程序已被捆绑。

此加载优化会导致挂载和卸载Micro Front-Ender的问题。我们需要通过创建或编辑config-overrides.js来禁用块,如下所示:

  1. module.exports = { 
  2.   webpack: (config, env) => { 
  3.     config.optimization.runtimeChunk = false
  4.     config.optimization.splitChunks = { 
  5.       cacheGroups: { 
  6.         default: false, 
  7.       }, 
  8.     }; 
  9.     return config; 
  10.   }, 
  11. }; 

之后,http:// localhost:4000 / asset-manifest.json显示没有块。

如果未从Create React应用程序生成React应用程序,则可以通过修改WebPack配置来完成步骤1和步骤2。

如果使用我们的改进的MicroFrontend.js,则不必在步骤1中使用React-App-Rewifirew,并且可以完全跳过步骤2。5步减少到3.5。详细信息描述于“您不必对微前端丢失优化”中。

此保存在此回购的ChunkOptimization分支中捕获。

第3步:在SRC / index.js中进行更改以定义渲染和卸载功能

让我们来看看浏览Micro前端的SRC / index.js:

  1. import 'react-app-polyfill/ie11'; 
  2. import React from 'react'; 
  3. import ReactDOM from 'react-dom'; 
  4. import App from './App'; 
  5. import { unregister } from './registerServiceWorker'; 
  6.  
  7. window.renderBrowse = (containerId, history) => { 
  8.   ReactDOM.render( 
  9.     <App history={history} />
  10.     document.getElementById(containerId), 
  11.   ); 
  12.   unregister(); 
  13. }; 
  14.  
  15. window.unmountBrowse = containerId => { 
  16.   ReactDOM.unmountComponentAtNode(document.getElementById(containerId)); 
  17. }; 

window.RenderBrowse和window.unmountBrowse定义。这些方法由容器的Microfrontend.js调用。需要为Create React应用程序的SRC / index.js 定义类似的方法。

  1. import React from 'react'; 
  2. import ReactDOM from 'react-dom'; 
  3. import './index.css'; 
  4. import App from './App'; 
  5. import * as serviceWorker from './serviceWorker'; 
  6.  
  7. // render micro frontend function 
  8. window.renderCreatereactapp = (containerId, history) => { 
  9.   ReactDOM.render( 
  10.     <App history={history}/>
  11.     document.getElementById(containerId) 
  12.   ); 
  13.   serviceWorker.unregister(); 
  14. }; 
  15.  
  16. // unmount micro frontend function 
  17. window.unmountCreatereactapp = containerId => { 
  18.   ReactDOM.unmountComponentAtNode(document.getElementById(containerId)); 
  19. }; 
  20.  
  21. // Mount to root if it is not a micro frontend 
  22. if (!document.getElementById('Createreactapp-container')) { 
  23.   ReactDOM.render(<App />, document.getElementById('root')); 
  24.  
  25. // If you want your app to work offline and load faster, you can change 
  26. // unregister() to register() below. Note this comes with some pitfalls. 
  27. // Learn more about service workers: https://bit.ly/CRA-PWA 
  28. serviceWorker.unregister(); 

从第7行到第19行,窗口.RenderCreateActApp和Window.unmountCreaterActApp正在添加。

第23线变为条件。如果它是一个独立的应用程序,它将被呈现为根元素。如果它是一个微型前端,它将通过window.rendercreateActapp呈现给ContainID。

第4步:使用src / setupproxy.js设置CORS规则

在Web浏览器中启动Micro前端时,我们获得了CORS错误:

  1. 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. 

必须通过创建或编辑src / setupproxy.js来设置以下代理。

  1. module.exports = app => { 
  2.   app.use((req, res, next) => { 
  3.     res.header('Access-Control-Allow-Origin', '*'); 
  4.     next(); 
  5.   }); 
  6. }; 

在进行第5步之前,我们为容器做了一些额外的工作。

在.env文件中,需要添加新的Host

React_App_CreateActApp_Host。端口4000需要匹配创建React App正在运行的Real Port。

  1. REACT_APP_BROWSE_HOST=http://localhost:3001 
  2. REACT_APP_RESTAURANT_HOST=http://localhost:3002 
  3. REACT_APP_CREATEREACTAPP_HOST=http://localhost:4000 
  4. REACT_APP_CONTENT_HOST=http://localhost:5000 

需要对.env.生产需要做类似的变化:

  1. REACT_APP_BROWSE_HOST=https://browse.demo.microfrontends.com 
  2. REACT_APP_RESTAURANT_HOST=https://order.demo.microfrontends.com 
  3. REACT_APP_CREATEREACTAPP_HOST=https://createreactapp.demo.microfrontends.com 
  4. REACT_APP_CONTENT_HOST=https://content.demo.microfrontends.com 

在App Header.is中添加导航链接,以使UI可访问。这是可选的。

  1. import React from 'react'; 
  2. import { NavLink } from 'react-router-dom'; 
  3. import './AppHeader.css'; 
  4.  
  5. const AppHeader = () => ( 
  6.   <header> 
  7.     <div className="center-column"> 
  8.       <h1> Feed me</h1> 
  9.     </div> 
  10.     <nav> 
  11.       <ol className="center-column"> 
  12.         <li> 
  13.           <NavLink to="/">Browse restaurants</NavLink> 
  14.         </li> 
  15.         <li> 
  16.           <NavLink to="/random">Surprise me</NavLink> 
  17.         </li> 
  18.         <li> 
  19.           <NavLink to="/createreactapp">Create React App</NavLink> 
  20.         </li> 
  21.         <li> 
  22.           <NavLink to="/about">About</NavLink> 
  23.         </li> 
  24.       </ol> 
  25.     </nav> 
  26.   </header> 
  27. ); 
  28.  
  29. export default AppHeader; 

将CreateAteActApp及其路由添加到Container的App.js中:

  1. import React from 'react'; 
  2. import { BrowserRouter, Switch, Route, Redirect } from 'react-router-dom'; 
  3. import AppHeader from './AppHeader'; 
  4. import MicroFrontend from './MicroFrontend'; 
  5. import About from './About'; 
  6.  
  7. const { 
  8.   REACT_APP_BROWSE_HOST: browseHost, 
  9.   REACT_APP_RESTAURANT_HOST: restaurantHost, 
  10.   REACT_APP_CREATEREACTAPP_HOST: createreactappHost, 
  11. } = process.env; 
  12.  
  13. let numRestaurants = 0
  14. fetch(`${process.env.REACT_APP_CONTENT_HOST}/restaurants.json`) 
  15.   .then(res => res.json()) 
  16.   .then(restaurants => { 
  17.     numRestaurants = restaurants.length; 
  18.   }); 
  19. const getRandomRestaurantId = () => 
  20.   Math.floor(Math.random() * numRestaurants) + 1; 
  21.  
  22. const Browse = ({ history }) => ( 
  23.   <MicroFrontend history={history} host={browseHost} name="Browse" /> 
  24. ); 
  25. const Restaurant = ({ history }) => ( 
  26.   <MicroFrontend history={history} host={restaurantHost} name="Restaurant" /> 
  27. ); 
  28. const Createreactapp = ({ history }) => ( 
  29.   <MicroFrontend history={history} host={createreactappHost} name="Createreactapp" /> 
  30. ); 
  31. const Random = () => <Redirect to={`/restaurant/${getRandomRestaurantId()}`} />
  32.  
  33. const App = () => ( 
  34.   <BrowserRouter> 
  35.     <React.Fragment> 
  36.       <AppHeader /> 
  37.       <Switch> 
  38.         <Route exact path="/" component={Browse} /> 
  39.         <Route exact path="/restaurant/:id" component={Restaurant} /> 
  40.         <Route exact path="/createreactapp" component={Createreactapp} /> 
  41.         <Route exact path="/random" render={Random} /> 
  42.         <Route exact path="/about" render={About} /> 
  43.       </Switch> 
  44.     </React.Fragment> 
  45.   </BrowserRouter> 
  46. ); 
  47.  
  48. export default App; 

现在让我们试着展示我们的微型前端。

  • 内容服务器:NPM启动。
  • 浏览Micro前端:NPM开始。
  • 餐厅订购微型前端:NPM开始。
  • Create React App Micro前端:NPM开始。
  • 容器:NPM开始。

转到localhost:3000 / createActapp来启动页面。

哎呀,React spinning 日志在哪里?

让我们重新审视http:// localhost:4000 / asset-manifest.json。Micro前端的徽标是一个单独的文件:

  1.   "files": { 
  2.     "main.js": "/static/js/bundle.js", 
  3.     "main.js.map": "/static/js/bundle.js.map", 
  4.     "index.html": "/index.html", 
  5.     "static/media/logo.svg": "/static/media/logo.5d5d9eef.svg" 
  6.   }, 
  7.   "entrypoints": [ 
  8.     "static/js/bundle.js" 
  9.   ] 

我们忘了抓住它!

查看此徽标SVG文件的来源,该文件被设置为/static/media/logo.5d5d9eef.svg。此文件可在Create React App(HTTPS:// localhost:4000)中使用,但不在容器中(http:// localhost:3000)。

这是我们的最后一步。

步骤5:在.env文件中配置内容主机并将其用来前缀静态内容

创建或编辑.env以设置内容主机:

  1. REACT_APP_CONTENT_HOST=http://localhost:4000 

当Micro前端使用静态内容时,它需要在HTML中的%React_App_Content_host%前缀,并在JavaScript中的

Process.env.reacect_app_content_host。

在这里,我们在src / app.js中更改了第9行:

  1. import React from 'react'; 
  2. import logo from './logo.svg'; 
  3. import './App.css'; 
  4.  
  5. function App() { 
  6.   return ( 
  7.     <div className="App"> 
  8.       <header className="App-header"> 
  9.         <img src={`${process.env.REACT_APP_CONTENT_HOST}${logo}`} className="App-logo" alt="logo" /> 
  10.         <p> 
  11.           Edit <code>src/App.js</code> and save to reload. 
  12.         </p> 
  13.         <a 
  14.           className="App-link" 
  15.           href="https://reactjs.org" 
  16.           target="_blank" 
  17.           rel="noopener noreferrer" 
  18.         > 
  19.           Learn React 
  20.         </a> 
  21.       </header> 
  22.     </div> 
  23.   ); 
  24.  
  25. export default App; 

使用此更改,徽标SVG文件以http:// localhost:4000前缀。

该应用程序现在正常工作。

原文链接:

https://betterprogramming.pub/5-steps-to-turn-a-random-react-application-into-a-micro-frontend-946718c147e7

 

责任编辑:赵宁宁 来源: 今日头条
相关推荐

2021-10-19 10:15:06

微软Windows 11Windows

2022-02-15 09:36:13

容器应用程序云服务

2020-03-31 22:09:01

React应用程序

2020-10-14 15:05:02

React应用程序

2011-08-10 09:31:33

开发iPhone应用程

2021-09-04 17:26:31

SpringBoot转换器参数

2010-08-13 13:05:30

Flex应用程序

2021-07-14 17:39:46

ReactRails API前端组件

2022-03-14 08:54:04

NetlifyHTMLReact

2017-11-10 14:00:39

Riverbed应用程序网络性能

2022-09-25 00:07:18

Python图形界面

2020-10-10 10:30:31

JavaScript开发技术

2022-07-19 16:59:25

安全漏洞Web

2009-07-29 10:24:52

HTM转换为PDF

2012-11-01 11:34:31

IBMdw

2018-03-23 09:29:56

深度学习神经网络前端设计模型

2021-12-24 16:59:14

前端Web框架

2020-03-20 19:37:03

JavascriptWeb前端

2018-10-12 10:51:15

LinuxChromebook应用程序

2011-09-02 09:51:59

HTML 5
点赞
收藏

51CTO技术栈公众号