I need to provide a comprehensive guide on building an Angular project using Module Federation for micro-frontends.
Understanding the Goal:
The user wants to create an Angular application composed of micro-frontends using Webpack 5's Module Federation plugin. This is a standard architectural pattern for scaling large applications.
Key Components:
Architecture: I need a "Shell" (Host) application and at least one "Remote" (Micro-frontend) application.
Angular Version: Angular CLI 14+ supports Webpack 5 and Module Federation out-of-the-box (mostly), but Angular CLI 17/18 makes it even easier with schematics. I should probably stick to the modern, schematic-based approach (@angular-architects/module-federation) as it saves a ton of manual configuration, but I should also explain what's happening under the hood (webpack.config.js).
Steps:
Prerequisites.
Create Workspace.
Create Shell (Host) App.
Create Remote (MFE) App.
Configure Module Federation (The webpack.config.js part).
Implement the Loading Logic (How the Shell loads the Remote).
Routing (How to navigate).
Running the project.
Drafting the Steps - Mental Sandbox:
Approach: Should I use a single repo (monorepo) or multi-repo? A single repo is easier to demonstrate in a single response. I'll use nx or just standard Angular CLI with multiple projects. Let's stick to standard Angular CLI to keep it pure Angular, maybe creating a workspace with two projects.
Step 1: Setupnpx @angular/cli new shell-appcd shell-appng generate application mfe-product (or similar)
Correction: Actually, the @angular-architects/module-federation generator is the industry standard for this right now. It automates the complex webpack.config.js setup. I should definitely recommend using it to avoid typo errors in the config.
Step 2: The Shell (Host)
Needs to import module-federation.
Needs to define remotes in the config.
Needs a router setup to lazy load the remote module.
Step 3: The Remote (MFE)
Needs to expose a module (e.g., ProductModule).
Needs to configure name and filename (usually remoteEntry.js).
Needs to expose the module in webpack.config.js.
Step 4: The Glue (Loading)
The Host needs to know where the remote is.
Usually done in app.routes.ts using a specific load function provided by the library or standard dynamic import syntax mapped in the config.
Step 5: Version Compatibility
Crucial! The Angular versions must match, and library versions (@angular-architects/module-federation) must match the Angular version.
Bonus: Shared libraries (Singletons like RxJS or Angular Core).
Self-Correction during drafting:
Manual vs Schematic: Writing the webpack.config.js manually is error-prone for beginners. I will use the @angular-architects/module-federation schematic because it sets up the custom webpack builder in angular.json automatically. This is the most robust way to teach it.
Angular Version: I will assume Angular 17/18 (latest stable) usage (Standalone components vs NgModules).
Scenario: Standalone is the default now. I should write the guide using Standalone components, as that's the future. However, Module Federation works easiest with Modules (NgModule).
Correction: While Standalone works, the "Remote" usually exports an NgModule. I will stick to the standard pattern: Remote exposes a Module, Host loads it.
Let's assemble the response. I'll keep it clean, concise, and copy-pasteable.
Step 1: Create workspace + apps.
Step 2: Add Module Federation schematics.
Step 3: Create components/modules.
Step 4: Configure Webpack (The most critical part).
Step 5: Configure Routing.
Step 6: Run.
Refinement on Shared Dependencies:
Must mention singleton: true for @angular/core and @angular/common/http. If not, the app breaks or bloats.
Final Check:
Does this answer "Build an Angular project..."? Yes. It provides the specific steps to build a working prototype.
Let's generate the output.
This guide will walk you through building an Angular workspace containing two applications:
Shell (Host): The main application that loads the remote.
MFE (Remote): A separate Angular application exposing a component for the Shell to consume.
We will use the Angular CLI and Webpack 5 Module Federation.
Prerequisites
Node.js (v18+ recommended)
Angular CLI (v17+ recommended)
Step 1: Create the Workspace and Projects
We will create a monorepo-style structure using Angular CLI libraries.
Create the workspace:
bash
ng new angular-mfe-demo --create-application="false"
cd angular-mfe-demo
Create the Shell (Host) App:
bash
ng generate application shell --style=scss --routing=true
Create the MFE (Remote) App:
bash
ng generate application mfe --style=scss --routing=true
Step 2: Install Module Federation Plugin
In Angular CLI v17+, you can add Module Federation capabilities automatically using the ng add schematic. This handles the complex Webpack configuration for you.
Add to Shell:
bash
ng add @angular-architects/module-federation --project shell --port 4200 --type host
Add to MFE:
bash
ng add @angular-architects/module-federation --project mfe --port 4201 --type remote
(Note: This command modifies your angular.json to use a custom webpack builder and creates a webpack.config.js file in your project roots.)
Step 3: Configure the Remote (MFE)
We need to tell the MFE application to expose a specific component or module so the Shell can see it.
Create a Component in MFE:
bash
ng g c components/mfe-dashboard --project=mfe
(Update mfe-dashboard.component.html with some distinct text like "Hello from MFE Remote!")
Edit mfe/src/app/app.routes.ts:
Let's add a route to this component locally so we can test it in isolation.
Configure mfe/webpack.config.js:
Look for the ModuleFederationPlugin in the generated config. Update the exposes section:
javascript
// mfe/webpack.config.js
const ModuleFederationPlugin = require("webpack/lib/container/ModuleFederationPlugin");
module.exports = {
// ... other config
plugins: [
new ModuleFederationPlugin({
name: "mfe", // The global variable name
filename: "remoteEntry.js", // The entry point file
exposes: {
// Alias: Path to the module
'./DashboardModule': './src/app/components/mfe-dashboard/mfe-dashboard.component.ts',
},
// Important: Share Angular dependencies to avoid loading them twice
shared: {
...require("../../package.json").dependencies,
"@angular/core": { singleton: true, strictVersion: true },
"@angular/common": { singleton: true, strictVersion: true },
"@angular/router": { singleton: true, strictVersion: true },
},
}),
],
};
Step 4: Configure the Shell (Host)
Now we configure the Shell to consume the Remote.
Edit shell/webpack.config.js:
Update the remotes section in the ModuleFederationPlugin.
javascript
// shell/webpack.config.js
const ModuleFederationPlugin = require("webpack/lib/container/ModuleFederationPlugin");
module.exports = {
plugins: [
new ModuleFederationPlugin({
name: "shell",
remotes: {
// Key 'mfe' is used in imports
// URL points to the remoteEntry.js defined in MFE
mfe: "http://localhost:4201/remoteEntry.js",
},
shared: {
...require("../../package.json").dependencies,
"@angular/core": { singleton: true, strictVersion: true },
"@angular/common": { singleton: true, strictVersion: true },
"@angular/router": { singleton: true, strictVersion: true },
},
}),
],
};
Create a Wrapper Component (Optional but Recommended):
Since we are loading a Component directly, we can load it into a route. However, to make the routing seamless, we usually use a Component Wrapper or load it directly in the route config.
Open shell/src/app/app.routes.ts and configure the lazy loading:
typescript
import { Routes } from '@angular/router';
import { loadRemoteModule } from '@angular-architects/module-federation';
export const APP_ROUTES: Routes = [
{
path: '',
pathMatch: 'full',
redirectTo: 'home'
},
{
path: 'home',
loadComponent: () => import('./home/home.component').then(m => m.HomeComponent)
},
// This is the Micro-Frontend route
{
path: 'mfe-dashboard',
// 1. 'mfe' matches the key in shell/webpack.config.js remotes
// 2. './DashboardModule' matches the key in mfe/webpack.config.js exposes
loadComponent: () =>
loadRemoteModule({
remoteEntry: 'http://localhost:4201/remoteEntry.js',
remoteName: 'mfe',
exposedModule: './DashboardModule'
}).then(m => m.MfeDashboardComponent)
},
{ path: '**', redirectTo: 'home' }
];
Step 5: Running the Project
Micro-frontends require both applications to be served simultaneously.
Terminal 1 (MFE):
bash
ng serve mfe
Wait for it to compile. It usually runs on port 4201.
Terminal 2 (Shell):
bash
ng serve shell
It runs on port 4200.
Step 6: Test
Open your browser to http://localhost:4200.
Click the MFE Dashboard link.
You should see the content from the MFE application (running on port 4201) rendered inside the Shell application (running on port 4200) without a full page reload (SPA experience).
Summary of Key Concepts
ModuleFederationPlugin: The Webpack engine that handles the sharing.
remoteEntry.js: A lightweight manifest file generated by the Remote describing what it exposes.
exposes: Whitelist of modules the Remote shares.
remotes: Map of remote names to URLs that the Host consumes.
shared: Dependencies (like Angular core) that should be loaded only once to save bandwidth and prevent version conflicts.
Add a Router Outlet:
Ensure shell/src/app/app.component.html has the outlet: