日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > windows >内容正文

windows

基于 Webpack5 Module Federation 的业务解耦实践

發布時間:2023/12/24 windows 29 coder
生活随笔 收集整理的這篇文章主要介紹了 基于 Webpack5 Module Federation 的业务解耦实践 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

我們是袋鼠云數棧 UED 團隊,致力于打造優秀的一站式數據中臺產品。我們始終保持工匠精神,探索前端道路,為社區積累并傳播經驗價值。

本文作者:貝兒

前言

本文中會提到很多目前數棧中使用的特定名詞,統一做下解釋描述

  • dt-common:每個子產品都會引入的公共包(類似 NPM 包)
  • AppMenus:在子產品中快速進入到其他子產品的導航欄,統一維護在 dt-common 中,子產品從 dt-common 中引入
  • Portal:所有子產品的統一入口
  • APP_CONF:子產品的一些配置信息存放

背景

由于迭代中,我們有很多需求都是針對 AppMenus 的,這些需求的生效需要各個子產品的配合,進行統一變更。現在的數棧前端的項目當中, AppMenus 的相關邏輯存在于 dt-common 中,dt-common 又以獨立的目錄存在于每個子項目中, 所以當出現這種需求的時候,變更的分支就包含所有的子產品,這給前端以及測試同學都帶來很多重復性的工作。

本文旨在通過 webpack5 Module Federation 的實踐,實現 AppMenus 與各個子產品的解耦,即 AppMenus 作為共享資源,將其從 dt-common 中分離出來,保證其更新部署無需其他子產品的配合。

本地實現

Portal 項目

  1. 拆分 AppMenus 到 Portal 下的 Components 中,Portal 內部引用 AppMenus 就是正常組件內部的引用
  2. 配置 Module Federation 相關配置,方便其他項目進行遠程依賴
const federationConfig = {
        name: 'portal',
        filename: 'remoteEntry.js',
        // 當前組件需要暴露出去的組件
        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);	
  1. dt-common 中修改 Navigator 組件引用 AppMenus 的方式,通過 props.children 實現

子產品項目

  1. 配置 Module Federation config
const federationConfig = {
    name: 'xxx',
    filename: 'remoteEntry.js',
    // 關聯需要引入的其他應用
    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'],
        },
    },
};
  1. 修改 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;
}
  1. 注意本地調試的時候,子產品中需要代理 Portal 的訪問路徑到 Portal 服務的端口下,才能訪問 Portal 暴露出來的組件的相關chunckjs
module.exports = {
    proxy: {
        '/portal': {
            target: 'http://127.0.0.1:8081', // 本地
            //target: 'portal 對應的地址', 本地 -〉 devops 環境
            changeOrigin: true,
            secure: false,
            onProxyReq: ProxyReq,
       },
    }
}

遠程部署

部署到服務器上,由于 Portal 項目中的 AppMenus 相當于是遠程組件,即共享依賴;子產品為宿主環境,所以部署的時候需要對應部署 Portal 項目與子產品。而在上述配置中,需要變更的是加載的地址。 Portal 項目中沒有需要變更的,變更的是子產品中的相關邏輯。

//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>
    );
}

如何調試

子產品本地 → Portal 本地

Portal 與某個資產同時在不同的端口上運行
Portal 無需變更,子產品需要以下相關的文件
在這種情況下 remoteApp 為本地啟動的 portal 項目本地環境;同時當我們啟動項目的時候需要將 /partal 的請求代理到本地環境

// proxy -> 代理修改
// header 引用的遠程地址 -> 修改

window.APP_CONF?.remoteApp = 'http://127.0.0.1:8081'

proxy: {
    '/portal': {
        target: 'http://127.0.0.1:8081'
    }
}

子產品本地 → Portal 的服務器環境

本地起 console 的服務
服務器上部署 Portal 對應的 Module Ferderation 分支
同上,只不過此時 Portal 已經部署了,remote 和代理地址只需要改成部署后的 Portal 地址即可

// proxy -> 代理修改
// header 引用的遠程地址 -> 修改

window.APP_CONF?.remoteApp = 'xxx'

proxy: {
    '/portal': {
        target: 'xxx'
    }
}

子產品服務器環境 → Portal 的服務器環境

子產品 && Portal 分別部署到服務器環境上
修改子產品的 config 的配置 ,添加 window.APP_CONF.remoteApp 到 Portal 的服務器環境

異常處理

  1. 當 Portal 部署不當,或者是版本不對應的時候,沒有 AppMenus 遠程暴露出來的話, 做了異常處理思路是: 當請求 remoteEntry.js 出現 error 的時候,是不會展示 AppMenus 相關組件的
  2. 當 Portal 已經部署,其他子產品未接入 Module Federation, 是不會影響到子產品的正常展示的;子產品當下使用的 應是 dt-common 中的 AppMenus

如何開發 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)".

發現報錯路徑為 portal/xxx,可以定位到是 AppMunes 發生了問題,導致原因子產品 React-Redux 和 Portal React-Redux 版本不一致導致的,需要在對應子產品 federationConfig 處理 react-redux 為共享

總結

本文主要從業務層面結合 webpack 5 Module Federation ,實現 AppMenus 的解耦問題。主要涉及 dt-common 、Portal、子產品的變更。通過解耦能夠發現我們對 AppMenus 的開發流程減少了不少,有效的提高了我們的效率。

最后

歡迎關注【袋鼠云數棧UED團隊】~
袋鼠云數棧UED團隊持續為廣大開發者分享技術成果,相繼參與開源了歡迎star

  • 大數據分布式任務調度系統——Taier
  • 輕量級的 Web IDE UI 框架——Molecule
  • 針對大數據領域的 SQL Parser 項目——dt-sql-parser
  • 袋鼠云數棧前端團隊代碼評審工程實踐文檔——code-review-practices
  • 一個速度更快、配置更靈活、使用更簡單的模塊打包器——ko
  • 一個針對 antd 的組件測試工具庫——ant-design-testing

總結

以上是生活随笔為你收集整理的基于 Webpack5 Module Federation 的业务解耦实践的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。