Lab 10: Module Federation

Time: 60 minutes | Level: Architect | Docker: node:20-alpine

Overview

Type-safe module federation: @module-federation/typescript for type exposure, ambient module declarations for federated modules, type-safe dynamic import(), import type with verbatimModuleSyntax, and declaration maps for source navigation.


Step 1: Module Federation Overview

Module Federation allows apps to share code at runtime:
  - Host app: consumes exposed modules from remotes
  - Remote app: exposes modules for hosts to consume
  - Shared: common packages (React, etc.) loaded once

Type challenge:
  Host app imports remote module → TypeScript has no types!
  Solution: @module-federation/typescript or ambient declarations

Step 2: Webpack Module Federation Config

// webpack.config.js (Remote App — "checkout")
const { ModuleFederationPlugin } = require('webpack').container;

module.exports = {
  plugins: [
    new ModuleFederationPlugin({
      name: 'checkout',
      filename: 'remoteEntry.js',
      exposes: {
        './CheckoutForm': './src/components/CheckoutForm',
        './CartSummary':  './src/components/CartSummary',
        './useCart':      './src/hooks/useCart',
      },
      shared: {
        react:     { singleton: true, requiredVersion: '^18.0.0' },
        'react-dom': { singleton: true, requiredVersion: '^18.0.0' },
      },
    }),
    // Auto-generate TypeScript types for exposed modules
    new FederatedTypesPlugin({
      federationConfig: {
        name: 'checkout',
        exposes: { './CheckoutForm': './src/components/CheckoutForm' },
      },
    }),
  ],
};

// webpack.config.js (Host App — "shell")
new ModuleFederationPlugin({
  name: 'shell',
  remotes: {
    checkout: 'checkout@http://localhost:3001/remoteEntry.js',
  },
  shared: { react: { singleton: true } },
}),

Step 3: Ambient Module Declarations

💡 Place remote type declarations in a dedicated src/types/remotes.d.ts file and commit it to the host repo. The remote team is responsible for keeping it in sync — or use @module-federation/typescript to automate this.


Step 4: Type-Safe Dynamic Import


Step 5: import type and verbatimModuleSyntax


Step 6: Declaration Maps for Source Navigation


Step 7: @module-federation/typescript Automation


Step 8: Capstone — Ambient Declaration Verification

📸 Verified Output:


Summary

Problem
Solution
Tooling

Remote module has no types

Ambient declare module

Manual .d.ts file

Types drift from remote

Auto-fetch types

@module-federation/typescript

Accidental runtime type import

verbatimModuleSyntax

tsconfig flag

Can't navigate to source

declarationMap: true

tsconfig flag

Type-safe lazy load

React.lazy() with typed import

TypeScript inference

Dynamic module path

Generic load function

Type parameter assertion

Last updated