基于Webpack5 Module Federation的業(yè)務(wù)解耦實(shí)踐示例
前言
本文中會(huì)提到很多目前數(shù)棧中使用的特定名詞,統(tǒng)一做下解釋描述
- dt-common:每個(gè)子產(chǎn)品都會(huì)引入的公共包(類似 NPM 包)
- AppMenus:在子產(chǎn)品中快速進(jìn)入到其他子產(chǎn)品的導(dǎo)航欄,統(tǒng)一維護(hù)在 dt-common 中,子產(chǎn)品從 dt-common 中引入
- Portal:所有子產(chǎn)品的統(tǒng)一入口
- APP_CONF:子產(chǎn)品的一些配置信息存放
背景
由于迭代中,我們有很多需求都是針對(duì) AppMenus 的,這些需求的生效需要各個(gè)子產(chǎn)品的配合,進(jìn)行統(tǒng)一變更。現(xiàn)在的數(shù)棧前端的項(xiàng)目當(dāng)中, AppMenus 的相關(guān)邏輯存在于 dt-common 中,dt-common 又以獨(dú)立的目錄存在于每個(gè)子項(xiàng)目中, 所以當(dāng)出現(xiàn)這種需求的時(shí)候,變更的分支就包含所有的子產(chǎn)品,這給前端以及測(cè)試同學(xué)都帶來(lái)很多重復(fù)性的工作。
本文旨在通過(guò) webpack5 Module Federation 的實(shí)踐,實(shí)現(xiàn) AppMenus 與各個(gè)子產(chǎn)品的解耦,即 AppMenus 作為共享資源,將其從 dt-common 中分離出來(lái),保證其更新部署無(wú)需其他子產(chǎn)品的配合。
本地實(shí)現(xiàn)
Portal 項(xiàng)目
- 拆分 AppMenus 到 Portal 下的 Components 中,Portal 內(nèi)部引用 AppMenus 就是正常組件內(nèi)部的引用
配置 Module Federation 相關(guān)配置,方便其他項(xiàng)目進(jìn)行遠(yuǎn)程依賴
const federationConfig = { name: 'portal', filename: 'remoteEntry.js', // 當(dāng)前組件需要暴露出去的組件 exposes: { './AppMenus': './src/views/components/app-menus', }, shared: { react: { singleton: true, eager: true, requiredVersion: deps.react }, 'react-dom': { singleton: true, eager: true, requiredVersion: deps['react-dom'], }, }, }; const plugins = [ ...baseKoConfig.plugins, { key: 'WebpackPlugin', action: 'add', opts: { name: 'ModuleFederationPlugin', fn: () => new ModuleFederationPlugin({ ...federationConfig }), }, }, ].filter(Boolean);
- dt-common 中修改 Navigator 組件引用 AppMenus 的方式,通過(guò) props.children 實(shí)現(xiàn)
子產(chǎn)品項(xiàng)目
配置 Module Federation config
const federationConfig = { name: 'xxx', filename: 'remoteEntry.js', // 關(guān)聯(lián)需要引入的其他應(yīng)用 remotes: { // 本地相互訪問采取該方式 portal: 'portal@http://127.0.0.1:8081/portal/remoteEntry.js', }, shared: { antd: { singleton: true, eager: true, requiredVersion: deps.antd, }, react: { singleton: true, eager: true, requiredVersion: deps.react, }, 'react-dom': { singleton: true, eager: true, requiredVersion: deps['react-dom'], }, }, };
修改 AppMenus 引用方式
const AppMenus = React.lazy(() => import('portal/AppMenus')); <Navigator {...this.props} > <React.Suspense fallback="loading"> <AppMenus {...this.props} /> </React.Suspense> </Navigator> // 需要 ts 定義 // typings/app.d.ts 文件 declare module 'portal/AppMenus' { const AppMenus: React.ComponentType<any>; export default AppMenus; }
注意本地調(diào)試的時(shí)候,子產(chǎn)品中需要代理 Portal 的訪問路徑到 Portal 服務(wù)的端口下,才能訪問 Portal 暴露出來(lái)的組件的相關(guān)chunckjs
module.exports = { proxy: { '/portal': { target: 'http://127.0.0.1:8081', // 本地 //target: 'portal 對(duì)應(yīng)的地址', 本地 -〉 devops 環(huán)境 changeOrigin: true, secure: false, onProxyReq: ProxyReq, }, } }
遠(yuǎn)程部署
部署到服務(wù)器上,由于 Portal 項(xiàng)目中的 AppMenus 相當(dāng)于是遠(yuǎn)程組件,即共享依賴;子產(chǎn)品為宿主環(huán)境,所以部署的時(shí)候需要對(duì)應(yīng)部署 Portal 項(xiàng)目與子產(chǎn)品。而在上述配置中,需要變更的是加載的地址。 Portal 項(xiàng)目中沒有需要變更的,變更的是子產(chǎn)品中的相關(guān)邏輯。
//remote.tsx import React from 'react'; function loadComponent(scope, module) { return async () => { // Initializes the share scope. This fills it with known provided modules from this build and all remotes await __webpack_init_sharing__('default'); const container = window[scope]; // or get the container somewhere else // Initialize the container, it may provide shared modules await container.init(__webpack_share_scopes__.default); const factory = await window[scope].get(module); const Module = factory(); return Module; }; } const urlCache = new Set(); const useDynamicScript = (url) => { const [ready, setReady] = React.useState(false); const [errorLoading, setErrorLoading] = React.useState(false); React.useEffect(() => { if (!url) return; if (urlCache.has(url)) { setReady(true); setErrorLoading(false); return; } setReady(false); setErrorLoading(false); const element = document.createElement('script'); element.src = url; element.type = 'text/javascript'; element.async = true; element.onload = () => { console.log('onload'); urlCache.add(url); setReady(true); }; element.onerror = () => { console.log('error'); setReady(false); setErrorLoading(true); }; document.head.appendChild(element); return () => { urlCache.delete(url); document.head.removeChild(element); }; }, [url]); return { errorLoading, ready, }; }; const componentCache = new Map(); export const useFederatedComponent = (remoteUrl, scope, module) => { const key = `${remoteUrl}-${scope}-${module}`; const [Component, setComponent] = React.useState(null); const { ready, errorLoading } = useDynamicScript(remoteUrl); React.useEffect(() => { if (Component) setComponent(null); // Only recalculate when key changes }, [key]); React.useEffect(() => { if (ready && !Component) { const Comp = React.lazy(loadComponent(scope, module)); componentCache.set(key, Comp); setComponent(Comp); } // key includes all dependencies (scope/module) }, [Component, ready, key]); return { errorLoading, Component }; }; //layout header.tsx const Header = () => { .... const url = `${window.APP_CONF?.remoteApp}/portal/remoteEntry.js`; const scope = 'portal'; const module = './AppMenus' const { Component: FederatedComponent, errorLoading } = useFederatedComponent( url, scope, module ); return ( <Navigator logo={<Logo />} menuItems={menuItems} licenseApps={licenseApps} {...props}> {errorLoading ? ( <WarningOutlined /> ) : ( FederatedComponent && ( <React.Suspense fallback={<Spin />}> {<FederatedComponent {...props} top={64} showBackPortal />} </React.Suspense> ) )} </Navigator> ); }
如何調(diào)試
子產(chǎn)品本地 → Portal 本地
Portal 與某個(gè)資產(chǎn)同時(shí)在不同的端口上運(yùn)行
Portal 無(wú)需變更,子產(chǎn)品需要以下相關(guān)的文件
在這種情況下 remoteApp 為本地啟動(dòng)的 portal 項(xiàng)目本地環(huán)境;同時(shí)當(dāng)我們啟動(dòng)項(xiàng)目的時(shí)候需要將 /partal 的請(qǐng)求代理到本地環(huán)境
// proxy -> 代理修改 // header 引用的遠(yuǎn)程地址 -> 修改 window.APP_CONF?.remoteApp = 'http://127.0.0.1:8081' proxy: { '/portal': { target: 'http://127.0.0.1:8081' } }
子產(chǎn)品本地 → Portal 的服務(wù)器環(huán)境
本地起 console 的服務(wù)
服務(wù)器上部署 Portal 對(duì)應(yīng)的 Module Ferderation 分支
同上,只不過(guò)此時(shí) Portal 已經(jīng)部署了,remote 和代理地址只需要改成部署后的 Portal 地址即可
// proxy -> 代理修改 // header 引用的遠(yuǎn)程地址 -> 修改 window.APP_CONF?.remoteApp = 'xxx' proxy: { '/portal': { target: 'xxx' } }
子產(chǎn)品服務(wù)器環(huán)境 → Portal 的服務(wù)器環(huán)境
子產(chǎn)品 && Portal 分別部署到服務(wù)器環(huán)境上
修改子產(chǎn)品的 config 的配置 ,添加 window.APP_CONF.remoteApp 到 Portal 的服務(wù)器環(huán)境
異常處理
- 當(dāng) Portal 部署不當(dāng),或者是版本不對(duì)應(yīng)的時(shí)候,沒有 AppMenus 遠(yuǎn)程暴露出來(lái)的話, 做了異常處理思路是: 當(dāng)請(qǐng)求 remoteEntry.js 出現(xiàn) error 的時(shí)候,是不會(huì)展示 AppMenus 相關(guān)組件的
- 當(dāng) Portal 已經(jīng)部署,其他子產(chǎn)品未接入 Module Federation, 是不會(huì)影響到子產(chǎn)品的正常展示的;子產(chǎn)品當(dāng)下使用的 應(yīng)是 dt-common 中的 AppMenus
如何開發(fā) AppMenus
問題記錄
依賴版本不一致
【Error】Could not find "store" in either the context or props of "Connect(N)". Either wrap the root component in a \<Provider>, or explicitly pass "store" as a prop to "Connect(N)".
發(fā)現(xiàn)報(bào)錯(cuò)路徑為 portal/xxx,可以定位到是 AppMunes 發(fā)生了問題,導(dǎo)致原因子產(chǎn)品 React-Redux 和 Portal React-Redux 版本不一致導(dǎo)致的,需要在對(duì)應(yīng)子產(chǎn)品 federationConfig 處理 react-redux 為共享
總結(jié)
本文主要從業(yè)務(wù)層面結(jié)合 webpack 5 Module Federation ,實(shí)現(xiàn) AppMenus 的解耦問題。主要涉及 dt-common 、Portal、子產(chǎn)品的變更。通過(guò)解耦能夠發(fā)現(xiàn)我們對(duì) AppMenus 的開發(fā)流程減少了不少,有效的提高了我們的效率。
以上就是基于Webpack5 Module Federation的業(yè)務(wù)解耦實(shí)踐示例的詳細(xì)內(nèi)容,更多關(guān)于Webpack5 Module Federation業(yè)務(wù)解耦的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
React中使用dnd-kit實(shí)現(xiàn)拖曳排序功能
在這篇文章中,我將帶著大家一起探究React中使用dnd-kit實(shí)現(xiàn)拖曳排序功能,由于前陣子需要在開發(fā) Picals 的時(shí)候,需要實(shí)現(xiàn)一些拖動(dòng)排序的功能,文中通過(guò)代碼示例介紹的非常詳細(xì),需要的朋友可以參考下2024-06-06react-router-domV6嵌套路由實(shí)現(xiàn)詳解
這篇文章主要為大家介紹了react-router-domV6嵌套路由實(shí)現(xiàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-01-01react?express實(shí)現(xiàn)webssh?demo解析
這篇文章主要為大家介紹了詳解react?express實(shí)現(xiàn)webssh?demo解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04React關(guān)于antd table中select的設(shè)值更新問題
這篇文章主要介紹了React關(guān)于antd table中select的設(shè)值更新問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-03-03React-Native左右聯(lián)動(dòng)List的示例代碼
本篇文章主要介紹了React-Native左右聯(lián)動(dòng)List的示例代碼,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-09-09