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

什么是微型前端方法?微前端术语首先在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. class MicroFrontend extends React.Component {
  3.   componentDidMount() {
  4.     const { name, host, document } = this.props;
  5.     const scriptId = `micro-frontend-script-${name}`;
  6.     if (document.getElementById(scriptId)) {
  7.       this.renderMicroFrontend();
  8.       return;
  9.     }
  10.     fetch(`${host}/asset-manifest.json`)
  11.       .then(res => res.json())
  12.       .then(manifest => {
  13.         const script = document.createElement('script');
  14.         script.id = scriptId;
  15.         script.crossOrigin = '';
  16.         script.src = `${host}${manifest['main.js']}`;
  17.         script.onload = this.renderMicroFrontend;
  18.         document.head.appendChild(script);
  19.       });
  20.   }
  21.   componentWillUnmount() {
  22.     const { name, window } = this.props;
  23.     window[`unmount${name}`](`${name}-container`);
  24.   }
  25.   renderMicroFrontend = () => {
  26.     const { name, window, history } = this.props;
  27.     window[`render${name}`](`${name}-container`, history);
  28.   };
  29.   render() {
  30.     return ;
  31.   }
  32. }
  33. MicroFrontend.defaultProps = {
  34.   document,
  35.   window,
  36. };
  37. export default MicroFrontend;

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

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

 
 
 
 
  1. ReactDOM.render(
  2.     document.getElementById(containerId));

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

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

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

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

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

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

 
 
 
 
  1. {
  2.   "name": "my-app",
  3.   "version": "0.1.0",
  4.   "private": true,
  5.   "dependencies": {
  6.     "@testing-library/jest-dom": "^4.2.4",
  7.     "@testing-library/react": "^9.4.0",
  8.     "@testing-library/user-event": "^7.2.1",
  9.     "react": "^16.12.0",
  10.     "react-dom": "^16.12.0",
  11.     "react-scripts": "3.4.0",
  12.     "react-app-rewired": "2.1.5"
  13.   },
  14.   "scripts": {
  15.     "start": "PORT=4000 react-app-rewired start",
  16.     "build": "react-app-rewired build",
  17.     "test": "react-app-rewired test",
  18.     "eject": "react-scripts eject"
  19.   },
  20.   "eslintConfig": {
  21.     "extends": "react-app"
  22.   },
  23.   "browserslist": {
  24.     "production": [
  25.       ">0.2%",
  26.       "not dead",
  27.       "not op_mini all"
  28.     ],
  29.     "development": [
  30.       "last 1 chrome version",
  31.       "last 1 firefox version",
  32.       "last 1 safari version"
  33.     ]
  34.   }
  35. }
  • 在第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. window.renderBrowse = (containerId, history) => {
  7.   ReactDOM.render(
  8.     ,
  9.     document.getElementById(containerId),
  10.   );
  11.   unregister();
  12. };
  13. window.unmountBrowse = containerId => {
  14.   ReactDOM.unmountComponentAtNode(document.getElementById(containerId));
  15. };

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

     Feed me

  8.     
  •     
  •       
  •         
  •           Browse restaurants
  •         
  •         
  •           Surprise me
  •         
  •         
  •           Create React App
  •         
  •         
  •           About
  •         
  •       
  •     
  •   
  • );
  • 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. const {
    7.   REACT_APP_BROWSE_HOST: browseHost,
    8.   REACT_APP_RESTAURANT_HOST: restaurantHost,
    9.   REACT_APP_CREATEREACTAPP_HOST: createreactappHost,
    10. } = process.env;
    11. let numRestaurants = 0;
    12. fetch(`${process.env.REACT_APP_CONTENT_HOST}/restaurants.json`)
    13.   .then(res => res.json())
    14.   .then(restaurants => {
    15.     numRestaurants = restaurants.length;
    16.   });
    17. const getRandomRestaurantId = () =>
    18.   Math.floor(Math.random() * numRestaurants) + 1;
    19. const Browse = ({ history }) => (
    20.   
    21. );
    22. const Restaurant = ({ history }) => (
    23.   
    24. );
    25. const Createreactapp = ({ history }) => (
    26.   
    27. );
    28. const Random = () => ;
    29. const App = () => (
    30.   
    31.     
    32.       
    33.       
    34.         
    35.         
    36.         
    37.         
    38.         
    39.       
    40.     
    41.   
    42. );
    43. export default App;

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

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

    哎呀,React spinning 日志在哪里?

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

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

    我们忘了抓住它!

    查看此徽标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. function App() {
    5.   return (
    6.     
    7.       
    8.         
    9.         

    10.           Edit src/App.js and save to reload.
    11.         

    12.         
    13.           className="App-link"
    14.           href="https://reactjs.org"
    15.           target="_blank"
    16.           rel="noopener noreferrer"
    17.         >
    18.           Learn React
    19.         
    20.       
    21.     
  •   );
  • }
  • export default App;
  • 使用此更改,徽标SVG文件以http:// localhost:4000前缀。

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

    网页标题:5个步骤将随机React应用程序转换为微前端
    文章来源:http://www.shufengxianlan.com/qtweb/news7/498657.html

    网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

    广告

    声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

    猜你还喜欢下面的内容

    品牌网站建设知识

    各行业网站