Skip to content

Instantly share code, notes, and snippets.

@brunos3d
Last active January 6, 2023 14:42
Show Gist options
  • Save brunos3d/80235047c74b27573234c774ed474ef8 to your computer and use it in GitHub Desktop.
Save brunos3d/80235047c74b27573234c774ed474ef8 to your computer and use it in GitHub Desktop.
How to declare types of federated components without the need to re-write the types of the components

How to declare types of federated components without the need to re-write the types

Given that you have the following component (ComponentA) exported from remote (remote-a) in your Webpack config:

// ...
new ModuleFederationPlugin(
  {
    name: 'remoteA',
    exposes: {
      './ComponentA': './components/ComponentA/index.tsx',
    },
    // ...
  });
// ...

If you are using Next.js add the following config to your next.config.js:

module.exports = {
  webpack(config, options) {
    const { isServer } = options;
    config.plugins.push(
      new NextFederationPlugin({
        name: 'remoteA',
        exposes: {
          './ComponentA': './components/ComponentA/index.tsx',
        },
        // ...
      })
    );

    return config;
  },
};

In your tsconfig.json file at the root of your workspace, add the path alias for the remote-a

{
  "compilerOptions": {
    "paths": {
      "@remote-a/*": ["apps/remote-a/*"]
    }
  }
}

Then, in your index.d.ts file of the target application (the remote that will consume the component), add the following export

declare module 'remoteA/ComponentA' {
  export * from '@remote-a/components/ComponentA';
}

Result

Bellow you can see the autocomplete working

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment