0

Looking at the new module federation available in webpack 5 this works fantastically in development scenarios but leads to configuration like the following example.

Is there a better way to handle this?

webpack.config.js

const searchSource = process.env.SEARCH ? "http://localhost:3001" : "http://search.mydomain.com";
const marketplaceSource = process.env.MARKETPLACE ? "http://localhost:3002" : "http://marketplace.mydomain.com";

package.json

scripts: {
    "develop-search": "cross-env SEARCH=true webpack serve --mode=development",
    "develop-marketplace": "cross-env MARKETPLACE=true webpack serve --mode=development",
}
Chris
  • 171
  • 1
  • 7

1 Answers1

1

I'm still playing around with things, but I can share what we do. First we create a separate configuration for mapping the different urls:

federationRemotes.json:

{
    "app1": {
        "prod": "https://app1.domain.com/remoteEntry.js",
        "stage": "https://app1-stage.domain.com/remoteEntry.js",
        "local": "http://localhost:3000/remoteEntry.js"
    },
    "app2": {
        "prod": "https://app2.domain.com/remoteEntry.js",
        "stage": "https://app2-stage.domain.com/remoteEntry.js",
        "local": "http://localhost:3000/remoteEntry.js"
    }
}
function getFederationRemotes() {
    const remotes = {}
    const federationRemotes = require('./federationRemotes.json')
    Object.keys(federationRemotes).forEach(remote => {
        const localUrl = (federationRemotes[remote]['local'] || federationRemotes[remote]['stage'])
        remotes[remote] = productionMode ? `${remote}@___FEDERATION_PLACEHOLDER_${remote}___` : `${remote}@${localUrl}`
    });
    return remotes;
}

and then in the plugin we configure the remotes as:

new ModuleFederationPlugin({
 remotes: getFederationRemotes()
}

During local development we either point to a remote on local if it is defined, or else default to our staging environment.

We then have some scripts that replace the ___FEDERATION_PLACEHOLDER_${remote}___ during our CI/CD deployment build.

Your needs may not be exactly the same, so you could tweak things a bit here and there. But managing the mapping of the remote urls to enviroments in an external configuration and using a function to read them and replace them in a generic way, makes it easier to manage for us.

Daniel Tabuenca
  • 13,147
  • 3
  • 35
  • 38