Set up webpack to pull JS file from local rather than via HTTP

webpack.config.js pulls remote js for Module Federation.

plugins: [
  new ModuleFederationPlugin({
    remotes: {
      'mfe1': "mfe1@http://xxxxxxxxxx.com/remoteEntry.js"
    }
  })
],

How can I use a local JS file in remotes or in addition to remotes? I have a simple react.js library in the other folder, with ./dist/browser/remote-entry.js file in it. I cannot publish to npm, so I’m trying to load it from local. Would it be something like:

plugins: [
  new ModuleFederationPlugin({
    remotes: {
      'mfe1': "../../myproject/dist/browser/remoteEntry.js"
    }
  })
],

Answer

The remotes entry is supposed to be a url that is accessible during run-time, not build-time. If it was only necessary during build-time, it would automatically imply that the remoteEntry gets bundled, which defeats the purpose of Webpack Module Federation (WMF for short).

You say:

webpack.config.js pulls remote js for Module Federation.

But I’m not sure what that is supposed to mean. Webpack does not “pull” the remote files at all. It tells the final build where to look, so that when your code (i.e. bundle.js) actually executes, it knows from where to load modules dynamically. This means that, in order for WMF to work, you still need to serve the file from your web server.

You primarily have two choices:

  1. If you don’t want dynamic loading of modules, just build your project without WMF.
  2. If you do want dynamic loading, then you need to tell webpack that remotes url. Ideally, you can get the actual server address from process.env, which you can provide via dotenv (or through many other means):

webpack.config.js

// ...
module.exports = {
  // ...
  plugins: [
    new ModuleFederationPlugin({
      remotes: {
        'mfe1': `mfe1@${process.env.REMOTE_HOST || 'http://localhost:8080'}/remoteEntry.js`
      }
    })
  ],
  // ...
};

.env

REMOTE_HOST=http://xxxxxxxxxx.com

Also, you might want to consider this article on how to deploy a WMF build.