rspack icon indicating copy to clipboard operation
rspack copied to clipboard

[Feature]: Module Federation supports runtime URLs

Open zimo888 opened this issue 2 years ago • 8 comments

What problem does this feature solve?

I previously raised an issue in the rsbuild repository discussing this request, and I received a reply suggesting that a new issue should be created here instead. https://github.com/web-infra-dev/rsbuild/issues/1876

Currently, the Module Federation URL in rspack is configured locally, and changing it to runtime would have the following effects:

  1. Modules can be pre-compiled and then placed on a CDN in advance, significantly reducing the size of the local build.
  2. Developers can proxy production environment code locally, making debugging easier.
  3. Some larger third-party libraries’ index.js files can be split and transformed into a Module Federation approach, configurable for runtime on-demand loading, reducing the size of the third-party libraries.

What does the proposed API of configuration look like?

 moduleFederation: {
    options: {
      name: 'host',
      remotes: {
        remote: 'remote@[window.entry.remote]',
        antd: 'antd@[window.entry.base]',
      },
    },
  }

Host source somewhere before loading main entry file

window.entry=  {
   remote: "[cdn_url]",
   base: "[cdn_url]",
}

//proxy modules from localStorage
const proxyEntry = localStorage.getItem('mf_entry')
if(proxyEntry){
     window.entry = {
          ...window.entry,
          ...JSON.parse(proxyEntry)
    }
}
import("./bootstrap");

And then we can use ast transform convert third party code to module federation

import {Button} from 'antd'

->

import {Button} from 'base/antd'

zimo888 avatar Apr 01 '24 05:04 zimo888

I guess this is what you need: https://webpack.js.org/concepts/module-federation/#promise-based-dynamic-remotes, this is also supported in Rspack

ahabhgk avatar Apr 03 '24 08:04 ahabhgk

Hey, the solution to this question might not be 100% obvious to anyone reading the answer above, so here is the code in question that loads the remote app based on what's in the window.entry.remote variable (eg: http://localhost:3002/remoteEntry.js):

import { dependencies } from "./package.json";
import type { Rspack } from "@rsbuild/core";

export const mfConfig: Rspack.ModuleFederationPluginOptions = {
  name: "host",
  remotes: {
    remote: `promise new Promise((resolve, reject) => {
      // This part depends on how you plan on hosting and versioning your federated modules
      const remoteUrl = window.entry.remote
      const script = document.createElement('script')
      script.src = remoteUrl
      script.onload = () => {
        // the injected script has loaded and is available on window
        // we can now resolve this Promise
        const proxy = {
          get: (request) => window.remote.get(request),
          init: (arg) => {
            try {
              return window.remote.init(arg)
            } catch(e) {
              console.log('remote container already initialized')
            }
          }
        }
        resolve(proxy)
      }
      script.onerror = (event) => { reject(event.error) }
      // inject this script with the src set to the versioned remoteEntry.js
      document.head.appendChild(script);
    })
    `,
  },
  shared: {
    ...dependencies,
    react: {
      singleton: true,
      requiredVersion: dependencies.react,
    },
    "react-dom": {
      singleton: true,
      requiredVersion: dependencies["react-dom"],
    },
  },
};

(config adapted from module-federation example at https://github.com/rspack-contrib/rspack-examples/blob/main/rsbuild/module-federation/host/module-federation.config.ts)

Ideally, the code that builds the promise would be located in a utility function or plugin...

foxaltus avatar May 30 '24 13:05 foxaltus

Is this already solved? I can't really tell how the above function can be mapped/scalable like ExternalTemplateRemotesPlugin? Not too familiar with the syntaxes, If we are having more than 10 remotes, how do we inject the promise without duplicating the whole section promise new Promise(() => {})?

esia-block avatar Jun 23 '24 13:06 esia-block

It's just strings promise new Promise(${commonPart})

ahabhgk avatar Jun 23 '24 16:06 ahabhgk

I wrote a helper function but I am having other issues right now, so someone else will have to check if this works:

function dynamicRemote(moduleName, urlExpression) {
  return `promise new Promise((resolve, reject) => {
      const urlValue = ${urlExpression};
      const remoteUrl = typeof urlValue === 'function' ? urlValue() : urlValue;
      const script = document.createElement('script');
      script.src = remoteUrl;
      script.onload = () => {
        const proxy = {
          get: (...args) => window.${moduleName}.get(...args),
          init: (shareScope, initScope) => {
            try {
              return window.${moduleName}.init(shareScope, initScope);
            } catch (e) {
              console.log('Remote container already initialized');
            }
          },
        };
        resolve(proxy);
      };
      script.onerror = (event) => { reject(event); };
      document.head.appendChild(script);
    })`;
}
new rspack.container.ModuleFederationPluginV1({
    name: "host1",
    filename: "remoteEntry.js",
    remotes: {
      app1: dynamicRemote("app1", `window.app1Url`), // same as: "app1@[window.app1Url]"
    },
    exposes: {},
    shared: [],
})

Source: https://webpack.js.org/concepts/module-federation/#promise-based-dynamic-remotes

pureliani avatar Sep 23 '24 09:09 pureliani

What problem does this feature solve?

I previously raised an issue in the rsbuild repository discussing this request, and I received a reply suggesting that a new issue should be created here instead. web-infra-dev/rsbuild#1876

Currently, the Module Federation URL in rspack is configured locally, and changing it to runtime would have the following effects:

  1. Modules can be pre-compiled and then placed on a CDN in advance, significantly reducing the size of the local build.
  2. Developers can proxy production environment code locally, making debugging easier.
  3. Some larger third-party libraries’ index.js files can be split and transformed into a Module Federation approach, configurable for runtime on-demand loading, reducing the size of the third-party libraries.

What does the proposed API of configuration look like?

moduleFederation: { options: { name: 'host', remotes: { remote: 'remote@[window.entry.remote]', antd: 'antd@[window.entry.base]', }, }, } Host source somewhere before loading main entry file

window.entry= { remote: "[cdn_url]", base: "[cdn_url]", }

//proxy modules from localStorage const proxyEntry = localStorage.getItem('mf_entry') if(proxyEntry){ window.entry = { ...window.entry, ...JSON.parse(proxyEntry) } } import("./bootstrap"); And then we can use ast transform convert third party code to module federation

import {Button} from 'antd'

->

import {Button} from 'base/antd'

How to solve it ? rspack mf v1

dxhsmwqcwelllee avatar May 21 '25 00:05 dxhsmwqcwelllee

@zimo888

dxhsmwqcwelllee avatar May 21 '25 01:05 dxhsmwqcwelllee

@zimo888

pureliani 's dynamicRemote helper worked for me.

@dxhsmwqcwelllee

zimo888 avatar May 21 '25 03:05 zimo888