Module Federation Not working with dynamic hooking the remote in webpack.config.js

Viewed 1095

I have module federation setup and working fine when I load the remotes upfront in index.html

Below works

index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <script src="http://localhost:8002/remoteEntry.js"></script>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

host webpack
{
            name: "home",
            library: {type: "var", name: "home"},
            filename: "remoteEntry.js",
            remotes: {
                nav: "dashboards",
            },
            shared: ["react", "react-dom"],
        }

remote webpack
{
            name: "dashboards",
            library: {type: "var", name: "dashboards"},
            filename: "remoteEntry.js",
            remotes: {},
            exposes: {
                Header: "./src/Header",
            },
            shared: ["react", "react-dom"],
        }

However this loads the JS File upfront which is undesireable. I was following examples where the library is dynamically loaded in webpack... Here is what I want to do

index.html
<!DOCTYPE html>
<html lang="en">
  <body>
    <div id="root"></div>
  </body>
</html>



host webpack
{

            name: "app-shell",
            filename: "remoteEntry.js",
            remotes: {
                dashboards: "dashboards@http://localhost:8002/remoteEntry.js",
            },
        }

remote webpack
{
            name: "dashboards",
            filename: "remoteEntry.js",
            remotes: {},
            exposes: {
                Header: "./src/Header.jsx",
            },
        }

I get error on the host app

Uncaught syntax error; Invalid or unexpected token:
module.exports = dashboards@http://localhost:8002/dist/remoteEntry.js;

JS Error

1 Answers

You're Remote Webpack exposes object is incorrect. You're missing the ./ in front of Header. Replace with this:

"./Header": "./src/Header.jsx"

Also, if that doesn't work, try removing the library section:

library: {type: "var", name: "dashboards"}

I think this changes the remoteType from var to script, which apparently helps.

Related