Search code examples
reactjswebpack-module-federation

How to catch loading script errors in Module Federation + React when using hooks


I have two react applications: The host and a remote. I am exporting a react hook from my remote. I want to detect when the remote is unavailable so I don't have access to the hook.

Currently, when that happens, I get a ScriptExternalLoadError: Loading script failed., and my UI goes down. What I want is to detect when it is not available so I don't call the function.

I know that with components I can do so using an Error Boundary and React Lazy Loading. How can I achieve this for a hook?

My host module federation config:

new ModuleFederationPlugin({
      name: "lf_sgf_mf_host",
      filename: "remoteEntry.js",
      remotes: {
        bonos: "lf_sgf_mf_bonos@http://localhost:3000/remoteEntry.js",
      },
      exposes: {
        "./hooks/useHostNavigation": "./src/hooks/useHostNavigation",
      },
      shared: {
        ...deps,
        react: {
          singleton: true,
          requiredVersion: deps.react,
        },
        "react-dom": {
          singleton: true,
          requiredVersion: deps["react-dom"],
        },
        "@auth0/auth0-spa-js": {
          singleton: true,
        },
      },
    })

My remote module federation config:

new ModuleFederationPlugin({
      name: "lf_sgf_mf_bonos",
      filename: "remoteEntry.js",
      remotes: {
        host: "lf_sgf_mf_host@http://localhost:8080/remoteEntry.js",
      },
      exposes: {
        "./SolicitudesAsignacion":
          "./src/pages/solicitudes-asignacion/SolicitudesAsignacion",
        "./hooks/useSwitchLanguage": "./src/hooks/useSwitchLanguage",
      },
      shared: {
        ...deps,
        react: {
          singleton: true,
          requiredVersion: deps.react,
        },
        "react-dom": {
          singleton: true,
          requiredVersion: deps["react-dom"],
        },
        "@auth0/auth0-spa-js": {
          singleton: true,
        },
      },
    }),

The problematic hook is useSwitchLanguage in the remote.

Thanks in advance!


Solution

  • I encountered a similar problem and managed to solve it as follows:

    const RemoteComponent = React.lazy(() =>
      import("remote/Welcome").catch(() => {
        return { default: () => <>Component unavailable!</> };
      })
    );
    

    If the script fails to load, you will get a replacement.