Build an Angular project that leverages micro-frontends with Module Federation.
- User
Build an Angular project that leverages micro-frontends with Module Federation.
Assistant
Refining The Approach
I'm currently fleshing out the structure of a potential guide. The core idea is still a step-by-step tutorial for Angular micro-frontends with Module Federation. However, I'm now considering how best to present each step, keeping the expert audience in mind. This includes balancing detailed explanations with concise code snippets.
Developing the Architecture
I've been solidifying the architecture. The guide will focus on creating an Angular project using Micro-frontends (MFE) via Webpack Module Federation. I've broken down the key components: host app, remote app, shared dependencies, and necessary tooling. The guide's structure will go step-by-step: setup, host creation, remote creation, module federation integration, configuring the remote, and then configuration of the host.
Implementing the Steps
I'm now deep into the actual implementation steps. I'm focusing on the practical "how-to" aspect of setting up the MFEs, starting with prerequisites like Angular CLI versions. Standalone components seem like the future, so I'm leaning toward showcasing those, but I'll make sure to cover modular structures too, for backward compatibility. I've begun drafting setup instructions, and then project creation and module federation integration via a handy library, while streamlining manual Webpack configuration where possible.
Constructing Remote Integration
I'm presently building out the remote module integration. I'm focusing on the remote MFE configuration, particularly the
exposessection of its Webpack config. I'm creating a sample feature module and component within the remote, which will be consumed by the host. Dynamic loading via a helper function will be emphasized for the host's module federation setup, as this simplifies the process. I'll highlight shared libraries, specifically how the library facilitates singleton and strict versioning. Finally, I'm refactoring code examples for the remote module to improve understanding and clarity.Addressing Remote Loading
I'm now focusing on the remote loading in the host application. Specifically, I'm integrating the remote module using a lazy-loading approach within the host's routing configuration. I'm ensuring the remoteEntry is correctly specified, and am refining the
loadChildrenimplementation to resolve the exposed module properly. I'm also addressing common pitfalls like asynchronous bootstrap and considering effective state sharing mechanisms between micro-frontends. Furthermore, I am considering CSS isolation strategies.Choosing CLI-Based Approach
I've decided to go with a pure Angular tutorial using the standard Angular CLI and
angular-architectsfor simplicity, as this is the most accessible for the target audience. I'll focus on dynamic loading with hardcoded URLs for demonstration, and keep Manifest-based federation as an advanced, optional topic.This is a step-by-step guide to building a Micro-frontend architecture using Angular and Webpack Module Federation.
We will use the standard community package,
@angular-architects/module-federation(created by Manfred Steyer), which abstracts away the complex Webpack configuration.The Architecture
- Shell (Host): The distinct main application running on port
4200. - MFE1 (Remote): A "Profile" feature application running on port
4201.
Step 1: Setup the Workspace
First, we create a workspace without a default application so we can house multiple projects cleanly.
# Create an empty workspace ng new mfe-demo --no-create-application cd mfe-demo # Generate the Host application (Shell) ng generate application shell --routing --style=scss # Generate the Remote application (MFE1) ng generate application mfe1 --routing --style=scss
Step 2: Add Module Federation
We will use the
@angular-architects/module-federationschematic. This automatically creates awebpack.config.jsand updates yourangular.jsonto use a custom builder.# Add federation to the Shell (Host) ng add @angular-architects/module-federation --project shell --type host --port 4200 # Add federation to MFE1 (Remote) ng add @angular-architects/module-federation --project mfe1 --type remote --port 4201Crucial Check: Look at your file structure. You should now see a
webpack.config.jsin the root of both projects.
Step 3: Create Code to Expose (in MFE1)
We need to create a Feature Module in the remote app that we want to share with the shell.
-
Create a Feature Module in
mfe1:ng g module profile --project mfe1 --routing ng g component profile/profile-view --project mfe1 -
Configure
profile-routing.module.ts(inprojects/mfe1/src/app/profile/):import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { ProfileViewComponent } from './profile-view/profile-view.component'; const routes: Routes = [ { path: '', component: ProfileViewComponent } ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule] }) export class ProfileRoutingModule { } -
Configure
webpack.config.js(inprojects/mfe1/): Update theexposessection to tell Webpack what to share.const { shareAll, withModuleFederationPlugin } = require('@angular-architects/module-federation/webpack'); module.exports = withModuleFederationPlugin({ name: 'mfe1', exposes: { // We are exposing the Module, which contains the routes and components './ProfileModule': './projects/mfe1/src/app/profile/profile.module.ts', }, shared: { ...shareAll({ singleton: true, strictVersion: true, requiredVersion: 'auto' }), }, });
Step 4: Consume the Remote (in Shell)
Now we configure the Shell to load the remote module dynamically.
-
Update
app-routing.module.ts(inprojects/shell/src/app/): We use theloadRemoteModuleutility.import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { loadRemoteModule } from '@angular-architects/module-federation'; const routes: Routes = [ { path: 'profile', loadChildren: () => loadRemoteModule({ type: 'module', remoteEntry: 'http://localhost:4201/remoteEntry.js', exposedModule: './ProfileModule', }).then((m) => m.ProfileModule), }, ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }Note: If you are using Standalone Components (Angular 15+), you can load components directly instead of modules.
-
Update
app.component.html(inprojects/shell/src/app/): Add the navigation link.<h1>Shell Application</h1> <ul> <li><a routerLink="/">Home</a></li> <li><a routerLink="/profile">Load Remote Profile</a></li> </ul> <router-outlet></router-outlet>
Step 5: Run the Applications
You need to run both applications simultaneously.
-
Open Terminal 1 (Remote):
ng serve mfe1(Wait for it to finish compiling)
-
Open Terminal 2 (Shell):
ng serve shell -
Test it:
- Open your browser to
http://localhost:4200. - Click "Load Remote Profile".
- You should see the
ProfileViewComponentrendered. It looks like it's part of the Shell, but the JS bundle is actually pulling from port4201.
- Open your browser to
Step 6: Shared Dependencies (Concept)
In both
webpack.config.jsfiles, you will see:shared: { ...shareAll({ singleton: true, strictVersion: true, requiredVersion: 'auto' }), },This is critical. It ensures that:
- Singleton: Angular (Core, Common, Router) is loaded only once. If the Shell loads Angular, the MFE uses the Shell's instance. This prevents "Mixing different versions of Angular" errors.
- StrictVersion: It warns/errors if the Shell and MFE have incompatible versions of dependencies.
Troubleshooting Common Issues
1.
remoteEntry.js404 Error- Ensure
mfe1is actually running. - Check the URL in
loadRemoteModule. It must point explicitly to the generated JS file (usuallyremoteEntry.js).
2. CORS Errors
- The Angular Architect's plugin usually handles this in dev mode. If you encounter this, ensure the Remote's
angular.jsonserve options (or webpack dev server info) allow cross-origin requests.
3. "Bootstrap" Error
- Module Federation requires an asynchronous bootstrap process.
- Look at your
main.ts. It likely contains onlyimport('./bootstrap');. - The actual startup logic is moved to
bootstrap.ts. If this file is missing ormain.tsinitializes the platform directly, Federation will fail. The schematic should have done this automatically for you.
- Shell (Host): The distinct main application running on port
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.