Other

This section is a collection of common issues related to the implementation of Module Federation in general(not specific error code). The main goal is to provide additional context and solution paths for beginners not familiar with the fundamental ways of how Module Federation is working at its core.

Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

Error Message

Browser Error Message

Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

You might have mismatching versions of React and the renderer (such as React DOM)

You might be breaking the Rules of Hooks

You might have more than one copy of React in the same app

Browser Error Message

Uncaught TypeError: Cannot read properties on null (reading useState)

Solution

This error is a React multi-instance problem, which usually occurs when react does not reuse the same instance. This problem can be avoided by setting shared and setting singleton: true singleton mode.

modern.config.js
{
    ...
    new ModuleFederationPlugin({
            ...,
         // Default basic configuration
         // shared: [
         //   'react',
         //   'react-dom',
         //   'my-custom-module'
         // ]

         // Configuration with more specificity
            shared: {
                react: { singleton: true, },
                'react-dom': { singleton: true, },
                'my-custom-module': { singleton: true, },
                ...
            },
        })
      ])
  }

Unable to compile federated types, Error: compile TS failed

Error Message

Browser Error Message

Unable to compile federated types, Error: compile TS failed, the original command is 'npx tsc --project file-path.json'.

Browser Error Message

Error: ENOENT: no such file or directory, open 'project-path/rspack_hmr/application-name/dist/@mf-types.zip'

Solution

  1. Execute npx tsc --project file-path.json according to the error message to solve all type problems encountered.
  2. Check your ModuleFederationPlugin config field exposes:
[modern|rspack|rsbuild|webpack].config.[js,ts]
new ModuleFederationPlugin({
    ...
    // Make sure both key and value start with "./"
    exposes: { './Foo': './src/<path-to-file>/Foo.tsx' },
    ...
  })

HMR failed

CORS warn

When exposes is set in the project, it will be regarded as a producer. To ensure that the producer resources can be loaded normally by consumers, @module-federation/modern-js and @module-federation/rsbuild-plugin will set Access-Control-Allow-Origin to * and issue a warning at the same time.

Solutions

  • [Modern.js]: Set devServer.headers value to the specified domain whitelist instead of *

  • [Rsbuild]: Set server.cors.origin value to the specified domain whitelist instead of *

A preload for 'http://resource-url' is found, but is not used because the request credentials mode does not match. Consider taking a look at crossorigin attribute.

Reason

When the producer URL is a manifest, loading this producer module will automatically preload the corresponding resources. If the above warning occurs, it is because the default preload does not configure credentials, while the actual load remote script carries the corresponding credentials, causing the preload to fail.

Solution

Add a runtime plugin via runtimePlugins and configure the crossorigin attribute in the createLink hook. Its value needs to be consistent with the actual load script.

For example, to modify the crossorigin attribute of the preloaded link to anonymous:

runtimePlugin.ts
import { ModuleFederationRuntimePlugin } from '@module-federation/runtime/types';

export default function MFLinkPlugin(): ModuleFederationRuntimePlugin {
  return {
    name: 'link-plugin',
    createLink({ url }) {
      const link = document.createElement('link');
      link.setAttribute('href', url);
      link.setAttribute('rel', 'preload');
      link.setAttribute('as', 'script');
      link.setAttribute('crossorigin', 'anonymous');
      return link
    }
  };
}

Multiple assets emit different content to the same filename mf-manifest.json

Reason

In Rspack 1.6.0-beta.0, we ported the manifest implementation to Rust. Upgrading Rspack without upgrading the MF-related packages will cause this error.

Solution

Upgrade the @module-federation scoped npm package to version 0.21.0 or later.

Browser compatibility

The Module Federation runtime was written in TypeScript and compiled to ES2021(Chrome 85 or higher is required). If you need to support lower versions of browsers, you can compile the code by yourself.

Rspack

Use builtin:swc-loader, for example:

{
    // The .cjs extension was required, because some Module Federation packages were imported as CommonJS modules.
    // e.g. `./node_modules/@module-federation/runtime-core/dist/index.cjs.cjs`
    test: /\.(?:m|c)?js$/,
    type: 'javascript/auto',
    use: [
        {
            loader: 'swc-loader',
            include: ['node_modules/@module-federation'],
            options: {
                jsc: {
                    parser: {
                        syntax: 'ecmascript',
                    },
                },
                env: {
                    targets: {
                        chrome: 69,
                    },
                    mode: 'usage',
                    coreJs: '3',
                },
                isModule: 'unknown',
            },
        },
    ],
}

Although you can set any targets you want, Module Federation use import() to load remote entries, so the browsers should support import()(Chrome 63).

Furthermore, moduleFederationDefaultRuntime.js in @rspack/core uses Array.flat method which can't be compiled by swc-loader. So the browsers should also support Array.flat(Chrome 69), if you use rspack as bundler.