reactjs - Webpack 模块联邦延迟加载 remoteEntry.js

标签 reactjs webpack react-router micro-frontend webpack-module-federation

当我将 React 与 ReactRouter 一起使用时,我可以延迟加载应用程序的入口文件吗?当我进入页面时,我拥有的每个应用程序都有很多对 remoteEntry.js 文件的请求。由于性能原因,我不想一开始就获取它。我想在访问特定应用程序的路径时加载它们。

enter image description here

最佳答案

您需要使用基于 promise 的动态 Remote 。

例如,与其将 Remote 定义为 URL:

module.exports = {
  plugins: [
    new ModuleFederationPlugin({
      name: 'host',
      remotes: {
        app1: 'app1@http://localhost:3001/remoteEntry.js',
      },
    }),
  ],
};

您可以在 webpack.config.js 中删除此引用并将远程定义为将在运行时解析的 promise :

const loadScope = (url: string, scope: string) => {
  const element: any = document.createElement('script');
  const promise = new Promise((resolve, reject) => {
    element.src = url;
    element.type = 'text/javascript';
    element.async = true;
    element.onload = () => resolve(window[scope]);
    element.onerror = reject;
  });
  document.head.appendChild(element);
  promise.finally(() => document.head.removeChild(element));
  return promise;
};

const loadModule = async (url: string, scope: string, module: string) => {
  try {
    const container = await loadScope(url, scope);
    await __webpack_init_sharing__('default');
    await container.init(__webpack_share_scopes__.default);
    const factory = await container.get(module);
    return factory();
  } catch (error) {
    console.error('Error loading module:', error);
    throw error;
  }
};

const MyApp = React.lazy(() =>
  loadModule(
    'http://localhost:3001/remoteEntry.js',
    'app1',
    './MyApp',
  ),
);

更多详情可以引用Webpack 5 documentation .

关于reactjs - Webpack 模块联邦延迟加载 remoteEntry.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68123199/

相关文章:

webpack - 需要 @google-cloud/language 中断 webpack ('Module Not Found' )

webpack - 如何通过代码拆分防止多次加载 vendor

javascript - react-router transitionTo(routeNameOrPath, [params[, query]]) 从 URL 隐藏查询

reactjs - 博览会和发布 channel ...如何识别开发/产品和真实 channel

javascript - 从 parent 到 child 的传递功能

javascript - react-native-really-awesome-button onPress 在状态改变时不更新功能

javascript - 如何在 Webpack 中对 CSS 文件进行版本控制并更新 list ?

Android WebView 上的 ReactJS 项目,图像未显示

reactjs - 自定义 React Router 渲染顺序

reactjs - ReactJS中点击按钮时如何获取父div的关键属性