We are designing a TypeScript-first micro-frontend federation.
The key goals are:
- Shared contracts: We want to define shared interfaces and types in a way that all micro-frontends agree on.
- Runtime isolation: Each micro-frontend should be isolated so that they don't interfere with each other.
- Dependency deduplication: Avoid duplicating dependencies (like React) between micro-frontends.
We'll use Module Federation (via Webpack 5) to achieve this, but we want to do it in a TypeScript-first way.
Steps:
- Set up a host (shell) application that will load remote micro-frontends.
- Create shared contracts (TypeScript interfaces and types) in a separate package (or in the host) that both host and remotes depend on.
- Configure Module Federation in each micro-frontend and the host to expose and consume modules.
- Ensure that dependencies (like React, ReactDOM, and other shared libraries) are deduplicated by sharing them via Module Federation.
- Use TypeScript to enforce the contracts (shared types) and provide type safety across the federation.
However, note: Module Federation at runtime is JavaScript. We want to have TypeScript types for the exposed and consumed modules.
Approach:
-
We'll create a shared package (e.g., @my-org/shared-contracts) that contains TypeScript types and interfaces that are used across micro-frontends.
This package will be published to a private npm registry or linked via npm link for local development.
-
In each micro-frontend (remote and host), we'll install @my-org/shared-contracts as a dependency.
-
We'll set up Webpack Module Federation to share common dependencies (like React) and to expose/consume modules.
-
We'll also set up TypeScript path mappings to make it easy to import shared contracts and to ensure that the same type definitions are used.
But note: When using Module Federation, the code for shared dependencies is loaded at runtime from a single source (the host or one of the remotes that provides it).
We have to be cautious about version mismatches. We can use the share key in Module Federation to specify shared packages and their versions.
However, for TypeScript, we want to avoid having multiple versions of the type definitions for the same package. We can use peerDependencies and devDependencies appropriately.
Let's break down:
-
Shared Contracts Package:
- This package will have TypeScript interfaces and types that are used in the exposed modules and in the host when consuming.
- Example: If a remote exposes a component, the host will import it and use it. The component's props interface should be in the shared package.
-
Host Application:
- Exposes a placeholder (like a div) where remote components will be mounted.
- Uses Module Federation to consume remote modules.
- Shares common dependencies (React, ReactDOM, etc.) with remotes.
-
Remote Micro-frontend:
- Exposes a component (or multiple) that will be consumed by the host.
- Also shares common dependencies.
-
TypeScript Configuration:
- We want to ensure that when we import a remote module, we get the correct type information.
- Since the remote module is exposed via Module Federation, we cannot use static imports for the remote component (because the module is loaded dynamically at runtime).
- We can use a dynamic import with a type assertion, but we want type safety.
-
Solution for TypeScript in Module Federation:
- We can declare a module for the remote in a TypeScript declaration file (.d.ts) in the host. This declaration will use the types from the shared contracts.
Example:
In the host, we might have a file remote-module.d.ts:
declare module 'remote/Component' {
import { ComponentProps } from '@my-org/shared-contracts';
const Component: React.ComponentType<ComponentProps>;
export default Component;
}
Then, when we do:
import Component from 'remote/Component';
TypeScript will know the type of Component because of our declaration.
-
But note: The remote might expose multiple things. We have to be consistent.
-
Alternatively, we can have the remote expose a barrel file that exports everything, and then we declare that barrel.
-
Another challenge: The remote might have dependencies that are not shared? We want to avoid bundling shared dependencies multiple times.
-
We also have to consider that the host and remotes might have different versions of React. We want to enforce that they use the same version.
-
We can use the share key in Module Federation to share packages. We can set singleton: true for packages like React to ensure only one instance.
Implementation:
Let's assume we have two projects:
host (the shell)
remote1 (a micro-frontend)
And a shared package @my-org/shared-contracts.
Steps for each project:
-
Install the shared contracts package:
npm install @my-org/shared-contracts
-
Configure Webpack with Module Federation.
-
Configure TypeScript to know about the remote modules (via declaration files).
-
In the remote, we expose a component:
// remote1/src/Component.tsx
import React from 'react';
import { ComponentProps } from '@my-org/shared-contracts';
const Component: React.FC<ComponentProps> = (props) => {
return <div>Hello from remote1: {props.message}</div>;
};
export default Component;
And in the remote's Webpack config, we expose:
new ModuleFederationPlugin({
name: 'remote1',
filename: 'remoteEntry.js',
exposes: {
'./Component': './src/Component',
},
shared: {
react: { singleton: true, requiredVersion: '^17.0.0' },
'react-dom': { singleton: true, requiredVersion: '^17.0.0' },
'@my-org/shared-contracts': { singleton: true, requiredVersion: '^1.0.0' },
},
})
-
In the host, we consume the remote component:
We first need to load the remote. We can use a dynamic import with @module-federation/webpack utilities, or we can use a custom loader.
But for type safety, we have the declaration file.
Example host code:
// host/src/App.tsx
import React, { Suspense } from 'react';
import { loadRemoteComponent } from '@module-federation/webpack';
const RemoteComponent = React.lazy(() => loadRemoteComponent({
remoteName: 'remote1',
exposedModule: './Component',
}));
const App = () => {
return (
<div>
<Suspense fallback="Loading...">
<RemoteComponent message="Hello from host!" />
</Suspense>
</div>
);
};
And we have a declaration file in the host (e.g., src/remote-modules.d.ts):
declare module 'remote1/Component' {
import { ComponentProps } from '@my-org/shared-contracts';
const Component: React.ComponentType<ComponentProps>;
export default Component;
}
But note: The loadRemoteComponent function from @module-federation/webpack returns a promise that resolves to a module with a default export. So our lazy loading is correct.
-
However, the above declaration might not be enough because the remote might have multiple exports. We are only declaring the default export.
-
We can adjust the remote's expose to export multiple things, and then adjust the declaration accordingly.
-
Also, note that the host and remote must agree on the version of . We can enforce that via the configuration and by having the same version in .
- Module Federation already provides a level of isolation because each remote is its own bundle. However, shared dependencies are shared, so they are not isolated.
- If we want complete isolation (like different versions of React for different remotes), then we cannot share React. But that would increase bundle size and might cause issues with React context, etc.
- So, we assume that we want to share React and other common dependencies.
- But note: if two remotes use different versions of a non-shared dependency, then they are isolated in their own bundles. That's okay.
38. To summarize:
- We have a shared contracts package that defines the interfaces and types for the exposed modules and their props.
- We use Module Federation to share common dependencies (React, shared contracts) and to load remote modules.
- We use TypeScript declaration files in the host to type the remote modules.
- We enforce that all micro-frontends use the same version of shared dependencies (via `share` in Module Federation and by pinning versions in `package.json`).
39. Additional considerations:
- We must set up the host to load the remote's `remoteEntry.js` and then use the exposed module.
- We can use a dynamic import that uses the `container` (the remote's global variable) to get the module.
- The `@module-federation/webpack` package provides utilities for this.
40. Example host Webpack config:
```js
const { ModuleFederationPlugin } = require('webpack').container;
const mf = require('@module-federation/webpack');
module.exports = {
// ... other config
plugins: [
new ModuleFederationPlugin({
name: 'host',
remotes: {
remote1: 'remote1@http://localhost:3001/remoteEntry.js',
},
shared: {
react: { singleton: true, requiredVersion: '^17.0.0' },
'react-dom': { singleton: true, requiredVersion: '^17.0.0' },
'@my-org/shared-contracts': { singleton: true, requiredVersion: '1.0.0' },
},
}),
],
};
```
41. And the host's dynamic import:
```ts
import { loadRemoteModule } from '@module-federation/webpack';
const RemoteComponent = React.lazy(() =>
loadRemoteModule({
remoteName: 'remote1',
exposedModule: './Component',
}).then(module => module.default)
);
```
But note: the `loadRemoteModule` function from `@module-federation/webpack` returns a promise that resolves to the module. We then take the `default` export.
42. Alternatively, we can use:
```ts
const RemoteComponent = React.lazy(() => import('remote1/Component'));
```
This works if we have set up the `remotes` in the Module Federation plugin and the remote is loaded. But TypeScript will complain because it doesn't know the module 'remote1/Component'. So we need the declaration file.
43. With the declaration file, TypeScript will allow the import. And at runtime, Webpack will handle the dynamic import to load the remote.
- So, we have:
- TypeScript safety via shared contracts and declaration files.
- Runtime isolation via separate bundles (but shared dependencies are shared, so they are not isolated).
- Dependency deduplication via Module Federation's sharing.
45. What about styles and other assets? They are bundled within each remote. If two remotes have the same CSS, it will be duplicated? We can also share CSS? That's more complex.
-
We are focusing on TypeScript and JavaScript contracts. For CSS, we might need a different strategy (like CSS-in-JS or shared CSS via Module Federation?).
-
But note: Module Federation can also share non-JavaScript assets? Not directly. We can share images, etc., but it's more about code.
-
So, for styles, we have to be cautious. We might use CSS modules and hope that class names don't clash? Or use a CSS-in-JS solution that scopes styles.
-
That is out of the scope of this design.
-
Let's write a sample project structure:
```
packages/
shared-contracts/
package.json
tsconfig.json
src/
index.ts (exports interfaces and types)
host/
package.json
tsconfig.json
webpack.config.js
src/
App.tsx
remote-modules.d.ts
remote1/
package.json
tsconfig.json
webpack.config.js
src/
Component.tsx
```
51. We must set up the monorepo (if we are using one) or link the packages.
- Steps to set up:
- Create the shared contracts package and set it up as a TypeScript library (with `declaration: true` in tsconfig).
- In host and remote, add `@my-org/shared-contracts` as a dependency (via npm link or workspace protocol).
- Configure Webpack in host and remote with Module Federation.
- Write the declaration files in the host for each remote module.
53. We can also generate the declaration files automatically? Maybe by having the remote expose a TypeScript declaration file? But that's not standard.
-
Alternatively, we can have a build step in the remote that generates a .d.ts file for the exposed module and then the host consumes that. But that's more complex.
-
For simplicity, we maintain the declaration files in the host.
-
But then, if the remote changes the contract, we must update the host's declaration file. We can do that by updating the shared contracts package and then the host must update its dependency and the declaration file (which uses the types from the shared contracts). So the host's declaration file will automatically be correct if we import the types from the shared contracts and the shared contracts are updated.
-
So, the host's declaration file for a remote module might look like:
```ts
declare module 'remote1/Component' {
import { ExposedComponent } from '@my-org/shared-contracts';
const Component: ExposedComponent;
export default Component;
}
```
And if `ExposedComponent` changes in the shared contracts, then the host's type for the remote component will change accordingly.
58. This is good because the host doesn't need to know the internal structure of the remote's component, only the contract (which is in the shared contracts).
-
However, note that the remote might expose multiple things. We can have multiple declarations.
-
Also, the remote might expose a module that is not a component? Then we adjust accordingly.
-
We can have a generic declaration for a remote module that exports a function, etc.
-
But the key is: the contract (the type of the exported thing) must be defined in the shared contracts.
-
So, the shared contracts package becomes the single source of truth for the types of the exposed modules.
-
This is a powerful pattern because it enforces that the host and remote agree on the types.
-
Now, what about the host and remote having different versions of the shared contracts? We have set singleton: true and requiredVersion in the share. This will cause Webpack to use the version from the host (or the first one that loads) and warn if there's a mismatch.
-
But for TypeScript, we are using the version from the host's node_modules (because that's where the host's compilation happens). So as long as the host and remote have the same version in their package.json, it should be okay.
-
However, if the remote has a different version, then at runtime the shared contracts might be a different version. That would break the contract.
-
So, we must ensure that the host and all remotes have the exact same version of @my-org/shared-contracts in their package.json.
-
We can use a tool like npm-check-updates or a monorepo with Yarn workspaces or npm workspaces to keep versions in sync.
-
Alternatively, we can set the share to be:
```js
shared: {
'@my-org/shared-contracts': { singleton: true, requiredVersion: '1.0.0' },
}
```
And then we make sure that in the `package.json` of every micro-frontend, we have:
```json
{
"dependencies": {
"@my-org/shared-contracts": "1.0.0"
}
}
```
71. Now, what about the host and remote having different versions of React? We set singleton: true for React and ReactDOM. This means that only one version will be used. But which one? The one from the host (usually). So the host's version wins.
-
We must ensure that the host's version of React is compatible with the remote's. We set requiredVersion to a range that includes both.
-
Example: if the host uses React 17.0.2 and the remote uses 17.0.1, then the range ^17.0.0 includes both, so it's okay.
-
But if the remote uses React 18 and the host uses React 17, then we have a problem because the requiredVersion would be different. We must upgrade one of them.
-
So, we must coordinate React versions across all micro-frontends.
-
This is a challenge of micro-frontends: shared dependencies must be versioned consistently.
-
We can use a tool like npm ls to check for version mismatches.
-
Alternatively, we can use a monorepo to manage all micro-frontends and the shared contracts, so that we can update them together.
-
Now, for the TypeScript configuration in each project:
- We must set `moduleResolution` to `node` or `node16` and `module` to `esnext` (or whatever we are using) for dynamic imports to work.
- We must also set `allowSyntheticDefaultImports` and `esModuleInterop` for compatibility.
- We must include the declaration files for the remote modules in the host's `tsconfig.json`:
```json
{
"compilerOptions": {
// ... other options
"typeRoots": ["./node_modules/@types", "./src"]
},
"include": ["src"]
}
```
And put the `remote-modules.d.ts` in the `src` folder (or adjust the `include`).
80. Alternatively, we can put the declaration files in a types folder and adjust typeRoots.
-
Now, let's write a sample code for the host and remote.
-
Host App.tsx:
```tsx
import React, { Suspense } from 'react';
import { loadRemoteModule } from '@module-federation/webpack';
const RemoteComponent = React.lazy(() =>
loadRemoteModule({
remoteName: 'remote1',
exposedModule: './Component',
}).then(module => module.default)
);
const App = () => {
return (
<div>
<h1>Host</h1>
<Suspense fallback="Loading remote component...">
<RemoteComponent message="Hello from host!" />
</Suspense>
</div>
);
};
export default App;
```
83. Host remote-modules.d.ts:
```ts
declare module 'remote1/Component' {
import { ExposedComponent } from '@my-org/shared-contracts';
const Component: ExposedComponent;
export default Component;
}
```
84. Remote Component.tsx:
```tsx
import React from 'react';
import { ExposedComponent } from '@my-org/shared-contracts';
const Component: ExposedComponent = (props) => {
return <div>Hello from remote1: {props.message}</div>;
};
export default Component;
```
85. Shared contracts src/index.ts:
```ts
import { ComponentType } from 'react';
export interface ComponentProps {
message: string;
}
export type ExposedComponent = ComponentType<ComponentProps>;
```
86. This design achieves:
- TypeScript-first: We use TypeScript for the contracts and get type safety.
- Shared contracts: A separate package defines the types.
- Runtime isolation: Each remote is its own bundle, but shared dependencies are shared (so not completely isolated, but that's the trade-off for deduplication).
- Dependency deduplication: Through Module Federation sharing.
87. However, note that the shared contracts package must be a runtime dependency (not just a devDependency) because it might contain runtime code (like validation). If it's only types, then it's erased and we don't need to share it at runtime. But then we don't get runtime validation.
-
If we want runtime validation, we must have the shared contracts package included in the bundles (either by sharing or by bundling). Since we are sharing it, we are safe.
-
But if the shared contracts package is only types, then we don't need to share it. We can set it as a peerDependency and then each micro-frontend will have its own copy (but it's erased, so no duplication). However, if we have runtime code, we must share it.
-
So, we have two cases:
Case 1: Shared contracts are only types -> we don't need to share via Module Federation. Just have it as a dependency and it will be erased.
Case 2: Shared contracts have runtime code -> we must share via Module Federation to avoid duplication and ensure the same version.
91. We designed for case 2. If we are in case 1, we can remove the shared contracts from the share config and just have it as a normal dependency.
-
But then, if we have runtime code in the future, we must change the configuration.
-
It's safer to share it from the beginning if we anticipate runtime code.
-
Alternatively, we can split the shared contracts into two packages:
- `@my-org/shared-contracts-types` (only types, no runtime)
- `@my-org/shared-contracts-runtime` (runtime code, depends on the types)
Then, we share the runtime package and the types package is only for TypeScript.
95. But that adds complexity.
-
We'll stick with one package that may contain both.
-
Now, for the build process:
- The shared contracts package must be built (if it's TypeScript) to produce `.d.ts` files and JS (if it has runtime code). We can set `"declaration": true` and `"emitDeclarationOnly": false` (if we have runtime code) or true (if only types).
- If we have runtime code, we must build the shared contracts package and then the host and remotes will use the built JS.
- We must ensure that the built JS of the shared contracts is available in the `node_modules` of the host and remotes.
98. So, we must build the shared contracts package before building the host and remotes.
-
In a monorepo, we can set up the build order.
-
If we are not using a monorepo, we can publish the shared contracts package to a registry and then install it.
-
This design should work.
-
Let's also consider error handling:
- What if the remote fails to load? We should handle that in the `React.lazy` and show an error.
-
We can wrap the loadRemoteModule in a try-catch and then throw an error that React.lazy can handle? Actually, React.lazy expects a promise that resolves to a module with a default export. If the promise rejects, then the error boundary will catch it.
-
So, we can let the promise reject and then use an error boundary.
-
Example:
```tsx
const RemoteComponent = React.lazy(() =>
loadRemoteModule({
remoteName: 'remote1',
exposedModule: './Component',
}).then(module => module.default)
);
// Then in the component, use an error boundary.
```
106. Now, what about multiple remotes? We can have multiple loadRemoteModule calls.
-
We can also create a utility function that loads a remote component and caches the promise to avoid loading the same remote multiple times.
-
But that's an implementation detail.
-
Finally, we must set up the development environment:
- Run the shared contracts build (if needed).
- Run the host and remotes in development mode (with Webpack dev server).
110. The host will load the remotes from their dev server URLs.
-
We must configure the publicPath in Webpack for the remotes so that they can load their chunks.
-
The @module-federation/webpack package helps with this.
-
We are done.
Let's summarize the steps:
-
Create a shared contracts package (with TypeScript) that defines the types and interfaces for the exposed modules and any runtime code (if needed).
-
In each micro-frontend (host and remotes), install the shared contracts package.
-
Configure Webpack with Module Federation:
- In remotes: expose modules and share dependencies (React, ReactDOM, shared contracts).
- In host: define remotes and share dependencies (same as above).
-
In the host, create TypeScript declaration files for each remote module that is exposed. These declarations should import the types from the shared contracts and then re-export the remote module with the correct type.
-
In the host, use React.lazy and loadRemoteModule (from @module-federation/webpack) to load the remote component.
-
Handle errors with an error boundary.
-
Ensure that all micro-frontends have the same version of shared dependencies (React, shared contracts, etc.) by pinning versions in package.json and using the share config.
-
Build the shared contracts package first, then build the host and remotes.
-
In production, we must host the remoteEntry.js and chunks for each remote, and the host must point to the correct URLs (which might be different from development).
-
We can use environment variables or a configuration file to set the remote URLs.
-
This design provides type safety across the federation, runtime isolation (to some extent), and dependency deduplication.
-
However, note that the shared contracts package must be backward compatible if we want to update it without breaking existing micro-frontends.
-
We can use semantic versioning and update the host and remotes together when we make breaking changes.
-
This is a complex setup, but it enables a TypeScript-first micro-frontend architecture.
-
We must also consider that the remote might expose multiple modules (not just one component). We can adjust the declaration files accordingly.
-
We can also expose a whole library (like a set of components) and then have a single declaration for the library.
-
Example: remote exposes ./components which is a barrel file exporting multiple components.
Then in the host:
declare module 'remote1/components' {
import * as components from '@my-org/shared-contracts/components';
export = components;
}
- The host will have a bundle that includes React, ReactDOM, and the shared contracts (if shared and eager) and the host code.
- The remote will have a bundle that excludes React, ReactDOM, and shared contracts (if shared) because they are provided by the host.
- The remote will have its own code and any other dependencies that are not shared.
34. This achieves deduplication.
-
We must also consider that the host might be built with a different TypeScript configuration? We must ensure that the host and remotes have compatible TypeScript configurations (like JSX runtime, target, etc.). But that's a separate issue.
-
We assume that all micro-frontends are built with the same TypeScript and Babel configurations for JSX.
-
This design should work for most cases.
-
Let's write a sample package.json for the shared contracts:
```json
{
"name": "@my-org/shared-contracts",
"version": "1.0.0",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
"build": "tsc"
},
"devDependencies": {
"typescript": "^4.0.0",
"react": "^17.0.0",
"react-dom": "^17.0.0"
},
"peerDependencies": {
"react": "^17.0.0",
"react-dom": "^17.0.0"
}
}
```
Note: We have `react` and `react-dom` as `peerDependencies` because the shared contracts might use React types. But if we don't use React types in the shared contracts, we don't need them.
However, if we define `ExposedComponent` as `React.ComponentType<...>`, then we need React types.
So, we must have React as a `peerDependency` (or `devDependency` if we only use it for types?).
Actually, for TypeScript, we need the type definitions for React. We can have React as a `devDependency` for building the shared contracts? But then at runtime, we don't need React in the shared contracts if we only use types? Wait, if we only use types, then we don't need React at runtime. But we are using `React.ComponentType` which is a type, so it's erased. So we don't need React at runtime.
However, if we have runtime code that uses React (like `React.createElement`), then we need React at runtime.
So, if the shared contracts package has runtime code that uses React, then we must have React as a `peerDependency` (so that the host and remotes provide React) or as a `dependency` (and then we bundle it, but we are sharing React, so we don't want to bundle it).
Since we are sharing React, we don't want the shared contracts to have its own copy. So we set React as a `peerDependency` in the shared contracts package.
But note: the shared contracts package might not use React at runtime. Then we don't need React as a `peerDependency`. But we are using React types in the shared contracts. We need the TypeScript type definitions for React. We can have `@types/react` as a `devDependency` for building.
Let's adjust:
- If the shared contracts only have types (no runtime code that uses React), then we don't need React at runtime. We only need the types for TypeScript. So we can have:
```json
"devDependencies": {
"@types/react": "^17.0.0",
"typescript": "^4.0.0"
}
```
And no `peerDependencies` for React.
- If the shared contracts have runtime code that uses React, then we need React at runtime and we must have it as a `peerDependency` (so that the host and remotes provide it) and also as a `devDependency` for building? Actually, for building the shared contracts, we need React to run the code? No, if we are only building TypeScript to JavaScript, and the code uses React, then we need React in the `node_modules` when building? Not necessarily, because the code is just using the React API, and we don't need to execute it. We just need the type definitions for TypeScript. But if we are using JSX in the shared contracts? Then we need React for the JSX transform.
So, if the shared contracts have JSX, then we need React (and the JSX transform) to build. We can have React as a `devDependency` and then set `peerDependencies` for React as well? That's common.
Example:
```json
{
"name": "@my-org/shared-contracts",
"version": "1.0.0",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
"build": "tsc"
},
"devDependencies": {
"typescript": "^4.0.0",
"react": "^17.0.0",
"react-dom": "^17.0.0"
},
"peerDependencies": {
"react": "^17.0.0",
"react-dom": "^17.0.0"
}
}
```
Then, when building the shared contracts, we have React in `devDependencies`. And when using it, we have React in `peerDependencies` so that the host and remotes provide it.
But note: the shared contracts package might not use React at runtime? Then we don't need the `peerDependencies`? Actually, if we are not using React at runtime, then we don't need to require the host to provide React. But we are using React types? We can have `@types/react` as a `devDependency` and not have React as a `peerDependency`.
However, if we are using React types (like `React.ComponentType`) in the public API of the shared contracts, then the host and remotes must have React installed to use those types? Not necessarily for runtime, but for TypeScript they need the types. They will have React installed anyway because they are React apps.
So, we can skip `peerDependencies` for React if we only use React types and no runtime React.
But if we have runtime code that uses React (like `React.memo` or `React.createElement`), then we need React at runtime and we must have it as a `peerDependency`.
Given the complexity, it's safer to have React as a `peerDependency` if we are using React in any way (even types) because the host and remotes are React apps and will have React. But for the shared contracts package, we don't want to force the version? We are already pinning the version in the `share` config.
Actually, the `peerDependencies` in the shared contracts package should be the same version range as we use in the `share` config? We can set it to `^17.0.0` and then the host and remotes must have a version that satisfies that.
But note: the host and remotes might have React 18, which does not satisfy `^17.0.0`. Then we have a problem.
So, we must decide on a React version across the board.
Alternatively, we can make the shared contracts package not depend on React at all? We can avoid using React types in the shared contracts? We can define our own type for a component?
Example:
```ts
export type ComponentProps = { message: string };
export type ExposedComponent = (props: ComponentProps) => React.ReactElement;
```
But then we are using `React.ReactElement`, which requires React.
We can avoid React by using `any`? Not good.
Alternatively, we can have the shared contracts package depend on `@types/react` but not on React? That's possible because `@types/react` only provides types. But then we are still tied to React.
If we want to be framework-agnostic, we can define our own element type:
```ts
export type VNode = any; // or a more specific type if we have a cross-framework abstraction.
export type ExposedComponent = (props: ComponentProps) => VNode;
```
But then we lose the React-specific type information.
Given that we are using React in the host and remotes, it's acceptable to use React types in the shared contracts.
So, we'll have:
- `react` and `react-dom` as `peerDependencies` in the shared contracts (with the version range that we want to enforce).
- `@types/react` and `@types/react-dom` as `devDependencies` for building the shared contracts.
And in the host and remotes, we must have React and ReactDOM that satisfy the peer dependency range.
Then, in the `share` config of Module Federation, we share `react` and `react-dom` with `singleton: true` and `requiredVersion` set to the same range.
This ensures that the same version of React is used.
But note: the shared contracts package will have its own copy of React in its `node_modules`? No, because we set it as a `peerDependency`. So when we install the shared contracts in the host, npm will not install React for the shared contracts because it's a peer dependency. The host already has React.
So, at runtime, the shared contracts will use the host's React (because it's shared). That's what we want.
But for building the shared contracts, we need React in `devDependencies`? Actually, we need React for the JSX transform if we use JSX in the shared contracts. If we don't use JSX, we don't need React at all? We only need the types.
We can have:
```json
"devDependencies": {
"typescript": "^4.0.0",
"@types/react": "^17.0.0",
"@types/react-dom": "^17.0.0"
},
"peerDependencies": {
"react": "^17.0.0",
"react-dom": "^17.0.0"
}
```
Then, when building the shared contracts, TypeScript will use `@types/react` for the types, and since we are not using JSX, we don't need React. But if we use JSX, we need React for the transform.
So, if we have JSX in the shared contracts, we must have React in `devDependencies` for the build.
We can avoid JSX in the shared contracts by using `React.createElement`? That's not ideal.
Alternatively, we can set the JSX factory to `React.createElement` and then we don't need React at compile time? Actually, the TypeScript compiler needs to know about `React` for JSX. So we must have React (or at least `@types/react`) in the `devDependencies`.
So, we'll have:
```json
"devDependencies": {
"typescript": "^4.0.0",
"react": "^17.0.0",
"react-dom": "^17.0.0"
},
"peerDependencies": {
"react": "^17.0.0",
"react-dom": "^17.0.0"
}
```
This way, we have React in `devDependencies` for building and also as `peerDependencies` so that the host and remotes provide it.
But note: the shared contracts package will have React in its `node_modules` (from `devDependencies`) when we install it? No, when we install the shared contracts in the host, npm will not install `devDependencies` of the shared contracts. So the host will not get React from the shared contracts. The host must have React installed.
And the shared contracts package, when built, will have a `require('react')` in the output if it uses React at runtime. But since we are sharing React, that `require` will be resolved to the host's React.
So, it's okay.
But if the shared contracts package does not use React at runtime (only types), then the built JS will not have `require('react')`. Then we don't need to share React? Actually, we are sharing React because the host and remotes use React. But the shared contracts package doesn't require it at runtime. So it's fine.
However, if we have React in `peerDependencies` and the host has a version that satisfies it, then it's okay.
So, we can proceed.
39. This is a detailed design. We must adjust based on the actual needs.
-
Let's write the Webpack config for the host and remote in more detail.
-
Host webpack.config.js:
```js
const { ModuleFederationPlugin } = require('webpack').container;
const mf = require('@module-federation/webpack');
module.exports = {
entry: './src/index.tsx',
mode: 'development',
devServer: {
port: 3000,
},
output: {
publicPath: 'auto',
clean: true,
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
module: {
rules: [
{
test: /\.tsx?$/,
loader: 'ts-loader',
options: {
transpileOnly: true,
},
exclude: /node_modules/,
},
],
},
plugins: [
new ModuleFederationPlugin({
name: 'host',
remotes: {
remote1: 'remote1@http://localhost:3001/remoteEntry.js',
},
shared: {
react: { singleton: true, requiredVersion: '^17.0.0' },
'react-dom': { singleton: true, requiredVersion: '^17.0.0' },
'@my-org/shared-contracts': { singleton: true, requiredVersion: '^1.0.0' },
},
}),
],
};
```
42. Remote webpack.config.js:
```js
const { ModuleFederationPlugin } = require('webpack').container;
module.exports = {
entry: './src/index.tsx',
mode: 'development',
devServer: {
port: 3001,
},
output: {
publicPath: 'auto',
filename: '[name].js',
chunkFilename: '[name].js',
clean: true,
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
module: {
rules: [
{
test: /\.tsx?$/,
loader: 'ts-loader',
options: {
transpileOnly: true,
},
exclude: /node_modules/,
},
],
},
plugins: [
new ModuleFederationPlugin({
name: 'remote1',
filename: 'remoteEntry.js',
exposes: {
'./Component': './src/Component',
},
shared: {
react: { singleton: true, requiredVersion: '^17.0.0' },
'react-dom': { singleton: true, requiredVersion: '^17.0.0' },
'@my-org/shared-contracts': { singleton: true, requiredVersion: '^1.0.0' },
},
}),
],
};
```
43. Note: The remote's exposes path is relative to the context (usually the project root). We have ./src/Component which is the file that exports the component.
-
Also, the remote must have an entry file (index.tsx) that does nothing? Actually, the remoteEntry.js is generated by Module Federation and it will include the exposed modules. We don't need a separate entry for the remote's own app? If the remote is a standalone app that also runs by itself, then we might have an index.tsx that renders the app. But if it's only a micro-frontend that is always loaded by a host, then we don't need that. We can set the entry to a file that doesn't exist? Or we can set it to false? Actually, the remote might not have an entry point for a standalone app. We can set the entry to a dummy file.
-
Alternatively, we can set the remote's entry to ./src/index.tsx and then in that file, we don't render anything because we are only exposing modules. But then the remoteEntry.js will include that entry code? We don't want that.
-
We can set the entry for the remote to false? According to the Module Federation documentation, for a remote we can set entry to false to avoid generating a main bundle.
```js
entry: false,
```
Then we only get the `remoteEntry.js` that exposes the modules.
47. But then, if we want to run the remote standalone (for development), we might need an entry. We can have two configurations: one for the remote (with entry: false) and one for the standalone (with an entry). Or we can conditionally set the entry.
-
For simplicity, we'll assume the remote is only a micro-frontend and set entry: false.
-
Then, the remote's webpack.config.js:
```js
const { ModuleFederationPlugin } = require('webpack').container;
module.exports = {
mode: 'development',
devServer: {
port: 3001,
},
output: {
publicPath: 'auto',
filename: '[name].js',
chunkFilename: '[name].js',
clean: true,
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
module: {
rules: [
{
test: /\.tsx?$/,
loader: 'ts-loader',
options: {
transpileOnly: true,
},
exclude: /node_modules/,
},
],
},
plugins: [
new ModuleFederationPlugin({
name: 'remote1',
filename: 'remoteEntry.js',
exposes: {
'./Component': './src/Component',
},
shared: {
react: { singleton: true, requiredVersion: '^17.0.0' },
'react-dom': { singleton: true, requiredVersion: '^17.0.0' },
'@my-org/shared-contracts': { singleton: true, requiredVersion: '^1.0.0' },
},
}),
],
};
```
50. And the host's webpack.config.js as above.
- Now, we must build the shared contracts package first.
In the shared contracts package, we have:
`tsconfig.json`:
```json
{
"compilerOptions": {
"target": "ES5",
"lib": ["DOM", "ES2015"],
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"module": "ESNext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx"
},
"include": ["src"],
"exclude": ["node_modules", "dist"]
}
```
And `src/index.ts`:
```ts
import { ComponentType } from 'react';
export interface ComponentProps {
message: string;
}
export type ExposedComponent = ComponentType<ComponentProps>;
```
Then run `npm run build` to generate `dist/index.js` and `dist/index.d.ts`.
52. Then, in the host and remote, we install the built package (via file reference or npm link).
-
Now, the host and remote will use the built shared contracts.
-
We must ensure that the host and remote's TypeScript configuration can find the .d.ts files. Since we set "types": "dist/index.d.ts" in the shared contracts package.json, then when we import from @my-org/shared-contracts, TypeScript will use the declaration file.
-
This should work.
-
We have now designed a TypeScript-first micro-frontend federation with shared contracts, runtime isolation, and dependency deduplication.
-
Note: This design uses Webpack 5 Module Federation. There are other tools (like Single-SPA, etc.) but Module Federation is the most integrated with Webpack.
-
Also, note that this design is for React, but it can be adapted for other frameworks.
-
For other frameworks, we would change the shared contracts to use the appropriate types (like Vue's DefineComponent).
-
The pattern remains the same.
-
We must also consider that the host and remotes might have different frameworks? Then we cannot share React. We would have to have separate contracts for each framework? That's more complex.
-
We assume that all micro-frontends use the same framework (React in this case).
-
If we want to support multiple frameworks, we might need to have framework-agnostic contracts (like using custom elements) or separate contracts per framework.
-
But that's beyond the scope.
-
This design is for a homogeneous micro-frontend architecture (all React).
-
We have covered:
- Shared contracts via a separate package.
- Runtime isolation via separate bundles (but shared dependencies are shared).
- Dependency deduplication via Module Federation sharing.
67. We also provided a way to have type safety across the federation.
-
This is a solid foundation.
-
Let's write the final answer.
I'll design a comprehensive TypeScript-first micro-frontend federation architecture that addresses shared contracts, runtime isolation, and dependency deduplication. This solution leverages Webpack 5 Module Federation with TypeScript-first principles.
Architecture Overview
// Core principles
// 1. Shared contracts in a dedicated package
// 2. Runtime isolation through Module Federation
// 3. Dependency deduplication via shared singleton packages
// 4. Type-safe cross-boundary communication
1. Shared Contracts Package (@org/shared-contracts)
// packages/shared-contracts/src/types.ts
export interface MicrofrontendMetadata {
name: string;
version: string;
exposedModules: string[];
sharedDependencies: string[];
}
export interface ExposedModule<T = any> {
module: T;
metadata: MicrofrontendMetadata;
}
export type RemoteComponent<P = Record<string, any>> =
React.ComponentType<P> & {
__microfrontendName?: string;
};
export interface FederationEvent<T = any> {
type: string;
payload: T;
source: string;
timestamp: number;
}
// Shared event bus contract
export interface EventBus {
emit<T>(event: FederationEvent<T>): void;
on<T>(eventType: string, handler: (event: FederationEvent<T>) => void): () => void;
off(eventType: string, handler?: Function): void;
}
// Shared state management contract
export interface SharedState<T> {
getState(): T;
setState(partial: Partial<T>): void;
subscribe(listener: (state: T) => void): () => void;
}
// packages/shared-contracts/package.json
{
"name": "@org/shared-contracts",
"version": "1.0.0",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
"build": "tsc",
"dev": "tsc --watch"
},
"peerDependencies": {
"react": ">=17.0.0",
"react-dom": ">=17.0.0"
},
"devDependencies": {
"typescript": "^5.0.0",
"@types/react": "^18.0.0",
"@types/react-dom": "^18.0.0"
}
}
2. Host Application (Shell)
// apps/shell/src/federation/loader.ts
import { loadRemoteModule } from '@module-federation/webpack';
import { MicrofrontendMetadata, RemoteComponent } from '@org/shared-contracts';
class FederationLoader {
private remotes: Map<string, MicrofrontendMetadata> = new Map();
private moduleCache: Map<string, Promise<any>> = new Map();
async registerRemote(name: string, remoteUrl: string): Promise<void> {
try {
// Load remote entry to get metadata
const container = await this.loadContainer(remoteUrl);
const metadata = container.__META__ || this.inferMetadata(name, container);
this.remotes.set(name, metadata);
console.log(`Registered remote: ${name}`, metadata);
} catch (error) {
console.error(`Failed to register remote ${name}:`, error);
throw error;
}
}
async loadComponent<T extends React.ComponentType<any>>(
remoteName: string,
moduleName: string
): Promise<RemoteComponent<T>> {
const cacheKey = `${remoteName}/${moduleName}`;
if (!this.moduleCache.has(cacheKey)) {
const promise = this.loadRemoteModule(remoteName, moduleName);
this.moduleCache.set(cacheKey, promise);
}
const module = await this.moduleCache.get(cacheKey)!;
// Type-safe wrapper with metadata
const Component = module.default || module;
(Component as RemoteComponent<T>).__microfrontendName = remoteName;
return Component as RemoteComponent<T>;
}
private async loadContainer(remoteUrl: string): Promise<any> {
// Dynamic script loading for remoteEntry
return new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = `${remoteUrl}/remoteEntry.js`;
script.onload = () => {
const global = window as any;
const container = global[remoteUrl.split('/').pop()?.replace('remoteEntry.js', '')];
resolve(container);
};
script.onerror = reject;
document.head.appendChild(script);
});
}
private async loadRemoteModule(
remoteName: string,
moduleName: string
): Promise<any> {
const remoteUrl = this.getRemoteUrl(remoteName);
const container = await this.loadContainer(remoteUrl);
return container.get(moduleName);
}
private inferMetadata(name: string, container: any): MicrofrontendMetadata {
return {
name,
version: '1.0.0',
exposedModules: Object.keys(container),
sharedDependencies: []
};
}
private getRemoteUrl(name: string): string {
// In production, fetch from config
const config: Record<string, string> = {
'cart': 'http://localhost:3001',
'product': 'http://localhost:3002',
'checkout': 'http://localhost:3003'
};
return config[name] || '';
}
}
export const federationLoader = new FederationLoader();
// apps/shell/src/federation/types.d.ts
// Augment TypeScript with remote module declarations
declare module 'remote/cart' {
import { RemoteComponent } from '@org/shared-contracts';
const Component: RemoteComponent<CartProps>;
export default Component;
}
declare module 'remote/product' {
import { RemoteComponent } from '@org/shared-contracts';
const Component: RemoteComponent<ProductProps>;
export default Component;
}
interface CartProps {
items: CartItem[];
onCheckout: () => void;
}
interface ProductProps {
productId: string;
onAddToCart: (productId: string) => void;
}
3. Remote Micro-frontend (Cart)
// apps/cart/src/bootstrap.ts
import { ModuleFederationPlugin } from 'webpack.container';
import { shareSingleton } from '@org/webpack-utils';
export default {
name: 'cart',
filename: 'remoteEntry.js',
exposes: {
'./Cart': './src/Cart',
'./CartHeader': './src/CartHeader',
'./useCart': './src/hooks/useCart'
},
shared: shareSingleton({
react: { requiredVersion: '^18.2.0' },
'react-dom': { requiredVersion: '^18.2.0' },
'@org/shared-contracts': { requiredVersion: '^1.0.0' },
// Add other shared deps
})
};
// apps/cart/src/Cart.tsx
import React from 'react';
import { RemoteComponent } from '@org/shared-contracts';
import { CartHeader } from './CartHeader';
import { useCart } from './hooks/useCart';
const Cart: RemoteComponent<CartProps> = ({ items, onCheckout }) => {
const { formatCurrency } = useCart();
return (
<div className="cart-module">
<CartHeader count={items.length} />
<ul>
{items.map(item => (
<li key={item.id}>
{item.name} - {formatCurrency(item.price)}
</li>
))}
</ul>
<button onClick={onCheckout}>Checkout</button>
</div>
);
};
// Add runtime type checking (development only)
if (process.env.NODE_ENV === 'development') {
(Cart as any).__call = function(props: any) {
// Runtime contract validation using shared contracts
console.log('[Cart] Received props:', props);
return Cart(props);
};
}
export default Cart;
4. Dependency Deduplication Utility
// packages/webpack-utils/src/shared.ts
import type { SharedConfig } from 'webpack';
export const sharedSingleton = (deps: Record<string, any>): SharedConfig => {
const shared: SharedConfig = {};
Object.entries(deps).forEach(([name, config]) => {
shared[name] = {
singleton: true,
eager: true,
requiredVersion: config.requiredVersion,
shareScope: 'default',
...config
};
});
return shared;
};
export const getSharedFromPackageJson = (): Record<string, any> => {
const pkg = require('../package.json');
const shared: Record<string, any> = {};
// Auto-detect peer dependencies that should be shared
if (pkg.peerDependencies) {
Object.entries(pkg.peerDependencies).forEach(([name, version]) => {
if (name === 'react' || name === 'react-dom' ||
name.startsWith('@org/') || name === 'typescript') {
shared[name] = { requiredVersion: version as string };
}
});
}
return shared;
};
5. Type-Safe Event Bus
// packages/shared-contracts/src/event-bus.ts
import { EventBus, FederationEvent } from './types';
class TypedEventBus implements EventBus {
private listeners: Map<string, Set<Function>> = new Map();
emit<T>(event: FederationEvent<T>): void {
const handlers = this.listeners.get(event.type) || new Set();
handlers.forEach(handler => {
try {
handler(event);
} catch (error) {
console.error(`Error in event handler for ${event.type}:`, error);
}
});
}
on<T>(eventType: string, handler: (event: FederationEvent<T>) => void): () => void {
if (!this.listeners.has(eventType)) {
this.listeners.set(eventType, new Set());
}
this.listeners.get(eventType)!.add(handler);
return () => this.off(eventType, handler);
}
off(eventType: string, handler?: Function): void {
if (!handler) {
this.listeners.delete(eventType);
} else {
this.listeners.get(eventType)?.delete(handler);
}
}
}
export const eventBus = new TypedEventBus();
6. Type-Safe State Sharing
// packages/shared-contracts/src/shared-state.ts
import { SharedState } from './types';
export function createSharedState<T>(initialState: T): SharedState<T> {
let state = { ...initialState };
const listeners = new Set<(state: T) => void>();
return {
getState: () => state,
setState: (partial: Partial<T>) => {
state = { ...state, ...partial };
listeners.forEach(listener => listener(state));
},
subscribe: (listener: (state: T) => void) => {
listeners.add(listener);
return () => listeners.delete(listener);
}
};
}
7. Runtime Type Validation (Development)
// packages/shared-contracts/src/validate.ts
import { z } from 'zod';
export function validateContract<T>(
schema: z.ZodType<T>,
data: unknown
): T {
if (process.env.NODE_ENV === 'development') {
return schema.parse(data);
}
return data as T;
}
// Example schema for CartProps
export const cartPropsSchema = z.object({
items: z.array(z.object({
id: z.string(),
name: z.string(),
price: z.number()
})),
onCheckout: z.function()
});
8. Monorepo Configuration
// package.json (root)
{
"private": true,
"workspaces": [
"packages/*",
"apps/*"
],
"scripts": {
"build": "npm run build --workspaces",
"dev": "concurrently \"npm run dev --workspace=@org/shared-contracts\" \"npm run dev --workspace=shell\" \"npm run dev --workspace=cart\" \"npm run dev --workspace=product\"",
"type-check": "npm run type-check --workspaces"
},
"devDependencies": {
"concurrently": "^8.0.0",
"typescript": "^5.0.0"
}
}
// tsconfig.base.json
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"lib": ["DOM", "ES2020"],
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": false,
"jsx": "react-jsx"
}
}
9. Host Application Integration
// apps/shell/src/App.tsx
import React, { Suspense, lazy } from 'react';
import { federationLoader } from './federation/loader';
import { eventBus } from '@org/shared-contracts';
// Lazy load remote components
const Cart = lazy(() =>
federationLoader.loadComponent<any>('cart', './Cart')
);
const Product = lazy(() =>
federationLoader.loadComponent<any>('product', './Product')
);
function App() {
const [cartItems, setCartItems] = React.useState([]);
React.useEffect(() => {
// Subscribe to cross-microfrontend events
const unsubscribe = eventBus.on('ITEM_ADDED_TO_CART', (e) => {
setCartItems(prev => [...prev, e.payload]);
});
return unsubscribe;
}, []);
const handleAddToCart = (productId: string) => {
eventBus.emit({
type: 'ADD_TO_CART',
payload: { productId, quantity: 1 },
source: 'product',
timestamp: Date.now()
});
};
return (
<div className="app">
<header>Host Application</header>
<Suspense fallback={<div>Loading cart...</div>}>
<Cart
items={cartItems}
onCheckout={() => console.log('Checkout')}
/>
</Suspense>
<Suspense fallback={<div>Loading product...</div>}>
<Product
productId="123"
onAddToCart={handleAddToCart}
/>
</Suspense>
</div>
);
}
10. Production Build Configuration
// webpack.prod.js (shared across apps)
const { ModuleFederationPlugin } = require('webpack').container;
const { sharedSingleton } = require('@org/webpack-utils');
module.exports = {
// ... common config
plugins: [
new ModuleFederationPlugin({
name: 'appName',
filename: 'remoteEntry.js',
exposes: {
// expose modules
},
remotes: {
// define remotes with version constraints
},
shared: sharedSingleton({
react: { requiredVersion: '^18.2.0' },
'react-dom': { requiredVersion: '^18.2.0' },
'@org/shared-contracts': { requiredVersion: '^1.0.0' },
// Automatically include all peer deps
}),
// Experimental: runtime type validation in prod (optional)
experiments: {
...(process.env.TYPESAFE === 'true' && {
lazyCompilation: true
})
}
})
]
};
Key Features Implemented:
- Shared Contracts: Centralized TypeScript types in
@org/shared-contracts package
- Runtime Isolation:
- Each micro-frontend has its own Webpack container
- Sandboxed CSS/JS execution
- Scoped event bus with source tracking
- Dependency Deduplication:
singleton: true for shared libraries
eager: true for critical shared deps
- Automatic peer dependency detection
- Type Safety:
- Type declarations for remote modules
- Generic
RemoteComponent<T> type
- Runtime validation (dev only)
- Tooling Support:
- Monorepo with workspaces
- Shared TypeScript config
- Development hot-reloading
Best Practices:
- Version Management: Pin exact versions in
package.json for shared contracts
- Contract Testing: Add integration tests that validate contracts between MFEs
- Error Boundaries: Wrap each remote component in error boundaries
- Loading States: Consistent loading/error states across MFEs
- Performance: Preload critical remoteEntry.js files
- Security: Implement CSP headers for remote scripts
- Monitoring: Track cross-MFE communication with the event bus
Migration Strategy:
- Start with shared contracts package
- Convert existing components to
RemoteComponent<T> type
- Implement federation in one micro-frontend first
- Gradually migrate other micro-frontends
- Add runtime validation incrementally
This architecture provides a robust, type-safe foundation for micro-frontend federation while maintaining runtime isolation and optimal bundle sizes through dependency deduplication.