Movatterモバイル変換


[0]ホーム

URL:


Skip to content
NxNxDocs
ContactTry Nx Cloud for free
GitHubYouTubeXDiscord

Advanced Angular Micro Frontends with Dynamic Module Federation

Dynamic Module Federation is a technique that allows an application to determine the location of its remote applications at runtime. It helps to achieve the use case of"Build once, deploy everywhere".

"Build once, deploy everywhere" is the concept of being able to create a single build artifact of your application and deploy it to multiple environments such as staging and production.

The difficulty in achieving this with a Micro Frontend Architecture using Static Module Federation is that our Remote applications will have a different location (or URL) in each environment. Previously, to account for this, we would have had to specify the deployed location of the Remote applications and rebuild the application for the target environment.

This guide will walk through how the concept of "Build once, deploy everywhere" can be easily achieved in a Micro Frontend Architecture that uses Dynamic Module Federation.

The aim of this guide is three-fold. We want to be able to:

  • Set up a Micro Frontend with Static Module Federation
  • Transform an existing Static Module Federation setup to use Dynamic Federation
  • Generate a new Micro Frontend application that uses Dynamic Federation

To achieve the aims, we will do the following:

  • Create a Static Federation Micro Frontend Architecture
  • Change theDashboard application to use Dynamic Federation
  • Generate a newEmployee Dashboard application that will use Dynamic Federation
    • It should use the existingLogin application.
    • It should use a newTodo application.

Here's the source code of the final result for this guide.

Example repository/Coly010/nx-ng-dyn-fed

To start with, we need to create a new Nx Workspace and add the Nx Angular plugin. We can do this easily with:

npx create-nx-workspace@latest ng-mf --preset=apps
NX Let's create a new workspace [https://nx.dev/getting-started/intro]
✔ Which CI provider would you like to use? · skip
✔ Would you like remote caching to make your build faster? · skip

Next run:

cdng-mf
npxnxadd@nx/angular

We need to generate two applications that support Module Federation.

We'll start with theAdmin Dashboard application which will act as a host application for the Micro-Frontends (MFEs):

nxg@nx/angular:hostapps/dashboard--prefix=ng-mf

The terminal examples in this guide will shownx being run as if it is installed globally. If you have not installed Nx globally (not required), you can use your package manager to run thenx local binary:

  • NPM:npx nx ...
  • Yarn:yarn nx ...
  • PNPM:pnpm nx ...

Thehost generator will create and modify the files needed to set up the Angular application.

Now, let's generate theLogin application as a remote application that will be consumed by theDashboard host application.

nxg@nx/angular:remoteapps/login--prefix=ng-mf--host=dashboard

Note how we provided the--host=dashboard option. This tells the generator that this remote application will be consumed by theDashboard application. The generator performed the following changes to automatically link these two applications together:

  • Added the remote to theapps/dashboard/module-federation.config.ts file
  • Added a TypeScript path mapping to the root tsconfig file
  • Added a new route to theapps/dashboard/src/app/app.routes.ts file

Let's take a closer look after generating each application.

For both applications, the generators did the following:

  • Created the standard Angular application files
  • Added amodule-federation.config.ts file
  • Added awebpack.config.ts andwebpack.prod.config.ts
  • Added asrc/bootstrap.ts file
  • Moved the code that is normally insrc/main.ts tosrc/bootstrap.ts
  • Changedsrc/main.ts to dynamically importsrc/bootstrap.ts(this is required for the Module Federation to load versions of shared libraries correctly)
  • Updated thebuild target in theproject.json to use the@nx/angular:webpack-browser executor(this is required to support passing a custom Webpack configuration to the Angular compiler)
  • Updated theserve target to use@nx/angular:dev-server(this is required as we first need Webpack to build the application with our custom Webpack configuration)

The key differences reside within the configuration of the Module Federation Plugin within each application'smodule-federation.config.ts.

We can see the following in theLogin micro frontend configuration:

apps/login/module-federation.config.ts
import { ModuleFederationConfig }from'@nx/module-federation';
constconfig:ModuleFederationConfig = {
name:'login',
exposes: {
'./Routes':'apps/login/src/app/remote-entry/entry.routes.ts',
},
};
exportdefault config;

Taking a look at each property of the configuration in turn:

  • name is the name that Webpack assigns to the remote application. Itmust match the name of the project.
  • exposes is the list of source files that the remote application exposes to consuming shell applications for their own use.

This config is then used in thewebpack.config.ts file:

apps/login/webpack.config.ts
import { withModuleFederation }from'@nx/module-federation/angular';
import configfrom'./module-federation.config';
exportdefaultwithModuleFederation(config, { dts:false });

We can see the following in theDashboard micro frontend configuration:

apps/dashboard/module-federation.config.ts
import { ModuleFederationConfig }from'@nx/module-federation';
constconfig:ModuleFederationConfig = {
name:'dashboard',
remotes: ['login'],
};
exportdefault config;

The key difference to note with theDashboard configuration is theremotes array. This is where you list the remote applications you want to consume in your host application.

You give it a name that you can reference in your code, in this caselogin. Nx will find where it is served.

Now that we have our applications generated, let's move on to building out some functionality for each.

We'll start by building theLogin application, which will consist of a login form and some very basic and insecure authorization logic.

Let's create a user data-access library that will be shared between the host application and the remote application. This will be used to determine if there is an authenticated user as well as providing logic for authenticating the user.

nxg@nx/angular:liblibs/shared/data-access-user

This will scaffold a new library for us to use.

We need an Angular Service that we will use to hold state:

nxg@nx/angular:serviceuser--project=data-access-user

This will create thelibs/shared/data-access-user/src/lib/user-auth.ts file. Change its contents to match:

libs/shared/data-access-user/src/lib/user-auth.ts
import { Injectable }from'@angular/core';
import { BehaviorSubject }from'rxjs';
@Injectable({ providedIn:'root' })
exportclassUserAuth {
private isUserLoggedIn=newBehaviorSubject(false);
isUserLoggedIn$=this.isUserLoggedIn.asObservable();
checkCredentials(username:string,password:string) {
if (username==='demo'&& password==='demo') {
this.isUserLoggedIn.next(true);
}
}
logout() {
this.isUserLoggedIn.next(false);
}
}

Now, export the service in the library's entry point file:

libs/shared/data-access-user/src/index.ts
...
export*from'./lib/user.service';

Let's set up ourentry.ts file in theLogin application so that it renders a login form. We'll importFormsModule and inject ourUserService to allow us to sign the user in:

apps/login/src/app/remote-entry/entry.ts
import { Component }from'@angular/core';
import { CommonModule }from'@angular/common';
import { FormsModule }from'@angular/forms';
import { UserService }from'@ng-mf/data-access-user';
import { inject }from'@angular/core';
@Component({
standalone:true,
imports: [CommonModule, FormsModule],
selector:'ng-mf-login-entry',
template:`
<div>
<form (ngSubmit)="login()">
<label>
Username:
<input type="text" name="username" [(ngModel)]="username" />
</label>
<label>
Password:
<input type="password" name="password" [(ngModel)]="password" />
</label>
<button type="submit">Login</button>
</form>
<div *ngIf="isLoggedIn$ | async">User is logged in!</div>
</div>
`,
styles: [
`
.login-app {
width: 30vw;
border: 2px dashed black;
padding: 8px;
margin: 0 auto;
}
.login-form {
display: flex;
align-items: center;
flex-direction: column;
margin: 0 auto;
padding: 8px;
}
label {
display: block;
}
`,
],
})
exportclassRemoteEntry {
private userService=inject(UserService);
username='';
password='';
isLoggedIn$=this.userService.isUserLoggedIn$;
login() {
this.userService.checkCredentials(this.username,this.password);
}
}

This could be improved with things like error handling, but for the purposes of this tutorial, we'll keep it simple.

Now let's serve the application and view it in a browser to check that the form renders correctly.

nxrunlogin:serve

We can see if we navigate a browser tohttp://localhost:4201 that we see the login form rendered.

If we type in the correct username and password(demo, demo), then we can also see the user gets authenticated!

Perfect! OurLogin application is complete.

Now let's update ourDashboard application. We'll hide some content if the user is not authenticated, and present them with theLogin application where they can log in.

For this to work, the state withinUserService must be shared across both applications. Usually, with Module Federation in Webpack, you have to specify the packages to share between all the applications in your Micro Frontend solution. However, by taking advantage of Nx's project graph, Nx will automatically find and share the dependencies of your applications.

Start by deleting theapp.html,app.css, andnx-welcome.ts files from theDashboard application. They will not be needed for this tutorial.

Next, let's add our logic to theapp.ts file. Change it to match the following:

apps/dashboard/src/app/app.ts
import { CommonModule }from'@angular/common';
import { Component, inject, OnInit }from'@angular/core';
import { Router, RouterModule }from'@angular/router';
import { UserService }from'@ng-mf/data-access-user';
import { distinctUntilChanged }from'rxjs/operators';
@Component({
standalone:true,
imports: [CommonModule, RouterModule],
selector:'ng-mf-root',
template:`
<div>Admin Dashboard</div>
<div *ngIf="isLoggedIn$ | async; else signIn">
You are authenticated so you can see this content.
</div>
<ng-template #signIn><router-outlet></router-outlet></ng-template>
`,
})
exportclassAppimplementsOnInit {
private router=inject(Router);
private userService=inject(UserService);
isLoggedIn$=this.userService.isUserLoggedIn$;
ngOnInit() {
this.isLoggedIn$
.pipe(distinctUntilChanged())
.subscribe(async(loggedIn)=> {
// Queue the navigation after initialNavigation blocking is completed
setTimeout(()=> {
if (!loggedIn) {
this.router.navigateByUrl('login');
}else {
this.router.navigateByUrl('');
}
});
});
}
}

Finally, make sure the application routes are correctly set up:

apps/dashboard/src/app/app.routes.ts
import { Route }from'@angular/router';
import { App }from'./app';
export constappRoutes:Route[] = [
{
path:'login',
loadChildren:()=>import('login/Routes').then((m)=> m.remoteRoutes),
},
{
path:'',
component: App,
},
];

We can now run both theDashboard andLogin applications:

nxservedashboard--devRemotes=login

Navigating tohttp://localhost:4200 should show theDashboard application with theLogin application embedded within it. If you log in, you should see the content change to show that you are authenticated.

This concludes the setup required for a Micro Frontend approach using Static Module Federation.

When serving module federation apps locally in dev mode, there'll be an error output to the console:import.meta cannot be used outside of a module. You'll see the error originates from thestyles.js script. It's a known error output, and as far as our testing has shown, it doesn't cause any breakages. It happens because the Angular compiler attaches thestyles.js file to theindex.html in a<script> tag withdefer.

It needs to be attached withtype=module, but Angular can't make that change because it breaks HMR. They also provide no way of hooking into that process for us to patch it ourselves.

The good news is that the error doesn't propagate to production because styles are compiled to a CSS file, so there's no erroneous JS to log an error.

It's worth stressing that no errors or breakages have been noted from our tests.

TheDashboard application is a Host application that loads the Remote applications at runtime based on their deployed locations when the application was built using Static Module Federation.

We want to change this so that theDashboard application can make a network request at runtime to find out the deployed locations of the Remote applications.

There are 3 steps involved with this:

  • Make a network request to fetch the locations of the Remote applications(the Remote Definitions).
  • Set the Remote Definitions so that webpack is aware of how to find the Remote applications when requested.
  • Change how we load the Remote applications so that webpack can fetch any required files correctly.

Perhaps one of the easiest methods of fetching the Remote Definitions at runtime is to store them in a JSON file that can be present in each environment. The Host application then only has to make a GET request to the JSON file.

We'll start by creating this file. Add amodule-federation.manifest.json file to thepublic/ folder in ourDashboard application with the following content:

apps/dashboard/public/module-federation.manifest.json
{
"login":"http://localhost:4201"
}

Next, open themain.ts file and replace it with the following:

apps/dashboard/src/main.ts
import { setRemoteDefinitions }from'@nx/angular/mf';
fetch('/module-federation.manifest.json')
.then((res)=> res.json())
.then((definitions)=>setRemoteDefinitions(definitions))
.then(()=>import('./bootstrap').catch((err)=> console.error(err)));

You'll notice that we fetch the JSON file and provide its contents to thesetRemoteDefinitions function we invoke next. This tells webpack where each of our remote applications has been deployed to!

At the moment, webpack is statically building our application, telling it at build time where our Remotes are. That is because they are specified in themodule-federation.config.ts file.

Open themodule-federation.config.ts file at the root of ourapps/dashboard/ folder and set theremotes property to be an empty array. It should look like this:

apps/dashboard/module-federation.config.ts
import { ModuleFederationConfig }from'@nx/module-federation';
constconfig:ModuleFederationConfig = {
name:'dashboard',
remotes: [],
};
exportdefault config;

Next, we need to change how our application attempts to load the Remote when it is routed to. Open theapp.routes.ts file under thesrc/app/ folder and apply the following changes:

apps/dashboard/src/app/app.routes.ts
import { Route }from'@angular/router';
import { loadRemoteModule }from'@nx/angular/mf';
import { App }from'./app';
export constappRoutes:Route[] = [
{
path:'login',
loadChildren:()=>
loadRemoteModule('login','./Routes').then((m)=> m.remoteRoutes),
},
{
path:'',
component: App,
},
];

TheloadRemoteModule helper method simply hides some logic that will check if the Remote application has been loaded, and if not, load it, and then requests the correct exposed routes from it.

That's all the changes required to replace Static Module Federation with Dynamic Module Federation.

Running:

nxservedashboard--devRemotes=login

Should result in the same behaviour as before, except that ourDashboard application is waiting until runtime to find out the deployed location of ourLogin application.

In the next section, we will see how Nx's generators can be used to automate a lot of this process for us!


Nx provides generators that aim to streamline the process of setting up a Dynamic Micro Frontend architecture.

To showcase this, let's create a new Host application that will use our previousLogin application as well as a newTodo Remote application.

Run the following command to generate a new Host application that is preconfigured for Dynamic Federation and add specify theLogin Remote application we want to add:

nxg@nx/angular:hostapps/employee--remotes=login--dynamic

This will generate:

  • Angular application
  • Webpack Configuration(webpack.config.ts)
  • Module Federation Configuration(module-federation.config.ts)
  • Micro Frontend Manifest File(module-federation.manifest.json)
  • Changes to the bootstrap of application to fetch the Micro Frontend Manifest, set the Remote Definitions and load theLogin application correctly

You should take a look at the files generated and see how theLogin Remote application was added to themodule-federation.manifest.json file and the slight changes tomain.ts andapp.routes.ts to load the Remotes dynamically.

We're going to demonstrate how when specifying a dynamic Host when adding a new Remote application, the Remote application will be added to the Host's Micro Frontend Manifest file correctly.

nxg@nx/angular:remoteapps/todo--host=employee

You'll note that this will generate the same output as theLogin Remote application in the previous guide. There's one difference. Because the Host application is using Dynamic Federation, the new Remote will be added to the Host'smodule-federation.manifest.json.

Dynamic Federation is the perfect way to solve the problem of"Build once, deploy everywhere". It can be used in tandem with CD solutions that involve spinning up environments for different stages of the release process without having to rebuild the application at all. The CD pipeline only ever needs to replace a JSON file on that environment with one that contains the correct values for the deployed locations of the remote applications.


[8]ページ先頭

©2009-2025 Movatter.jp