Module Federation in Webpack 5 lets apps share code with each other while running. In Angular, this makes it easy to break an app into smaller parts that work together smoothly.
Micro Frontend Architecture – Split large applications into smaller, independent parts.
Faster Build Times – Each team can work on a separate module without affecting the entire app.
Dynamic Updates – Load the latest version of a module without redeploying the entire application.
Code Sharing – Avoid duplicating dependencies and share common components across apps.
1. Host and Remote Applications
Host: The main shell application that loads remote modules.
Remote: The standalone applications or modules that expose functionality to the host.
2. Configuration in Webpack
Angular uses Webpack’s Module Federation Plugin to enable this functionality. The setup involves:
Declaring which modules should be shared.
Exposing specific components or services.
Dynamically loading modules into the host application.
1. Install Dependencies
Run the following command to set up Webpack 5 in an Angular project:ng add @angular-architects/module-federation
2. Configure the Remote App (webpack.config.js)
In the remote application, define which components or modules should be exposed:
const { ModuleFederationPlugin } = require('webpack').container;module.exports = {plugins: [new ModuleFederationPlugin({name: 'remoteApp',filename: 'remoteEntry.js',exposes: {'./RemoteModule': './src/app/remote/remote.module.ts',},}),],};
3. Configure the Host App (webpack.config.js)
Now, the host application must load the remote module dynamically:
const { ModuleFederationPlugin } = require('webpack').container;module.exports = {plugins: [new ModuleFederationPlugin({remotes: {remoteApp: 'remoteApp@http://localhost:4201/remoteEntry.js',},}),],};
4. Load Remote Module in Host App
Modify app-routing.module.ts in the host app to load the remote module:
import { loadRemoteModule } from '@angular-architects/module-federation';const routes: Routes = [{path: 'remote',loadChildren: () =>loadRemoteModule({remoteEntry: 'http://localhost:4201/remoteEntry.js',remoteName: 'remoteApp',exposedModule: './RemoteModule',}).then((m) => m.RemoteModule),},];Module Federation in Angular enables the creation of micro frontends, allowing for faster build times, dynamic updates, and efficient code sharing. By breaking down large applications into smaller, independent parts, development teams can work more efficiently and maintain a scalable codebase.
Ready to transform your business with our technology solutions? Contact Us today to Leverage Our Angular Expertise.
Contact Us