Angular CLI Configuração

Este guia explains como para integrate Module Federation com Angular CLI. O @angular-architects/module-federation plugin é usado para assist com este integração.

Prerequisites

  • Angular CLI: Versão 10 ou higher.
  • Plugin Instalação: Instale o @angular-architects/module-federation plugin.

Instalação

To começa, configure o Angular CLI para usar Module Federation during o build phase. Uma custom builder é needed para unlock Module Federation's potential.

O @angular-architects/module-federation pacote fornece este custom builder. Use o ng add comando para incorporate it em your projetos:

Angular CLI
Nx Cli
ng add @angular-architects/module-federation --project shell --port 4200 --type host
ng add @angular-architects/module-federation --project mfe1 --port 4201 --type remote

O --type argument, introduced em versão 14.3, ensures esse apenas o necessário configuração é generated.

Shell (Host) Configuração

O Shell (Host) é crucial for Module Federation integração. Este section configures o Shell para suporte lazy-carregamento de uma FlightModule por meio de routing.

Routing Configuração

Start by defining a aplicação rotas, specifying uma lazy-carregado FlightModule usando uma virtual caminho:

export const APP_ROUTES: Routes = [
  {
    path: '',
    component: HomeComponent,
    pathMatch: 'full'
  },
  {
    path: 'flights',
    loadChildren: () => import('mfe1/Module').then(m => m.FlightsModule)
  },
];

In este configuração, o caminho 'mfe1/Module' é uma virtual representation, indicating it doesn't physically exist within o Shell aplicação. Instead, it's uma reference para um módulo em uma separate projeto.

TypeScript Typing

Crie uma tipo definition para o virtual caminho:

// decl.d.ts
declare module 'mfe1/Module';

Este helps o TypeScript compiler understand o virtual caminho.

Webpack Configuração

Instruct Webpack para resolve all caminhos prefixed com mfe1 para uma remote projeto. Este é done no webpack.config.js arquivo:

const { shareAll, withModuleFederationPlugin } = require('@angular-architects/module-federation/webpack');

module.exports = withModuleFederationPlugin({

   remotes: {
     "mfe1": "http://localhost:4201/remoteEntry.js",
   },

   shared: {
     ...shareAll({ singleton: true, strictVersion: true, requiredVersion: 'auto' }),
   },

});

No remotes section, o caminho mfe1 é mapped para o remote micro-frontend's ponto de entrada. Este ponto de entrada, generated by Webpack, contains essential information for interacting com o micro-frontend.

For desenvolvimento, hardcoding o remote entry's URL é enough. However, uma dynamic approach é necessário for production. O concept de dynamic remotes é further explored em uma dedicated documentation page on Dynamic Remotes.

  • O shared propriedade specifies o npm pacotes para ser shared entre o Shell e o micro-frontend(s). Usando o shareAll helper método, all dependências listed em your package.json são shared. While este facilitates uma quick configuração, it may lead para um excessive number de dependências compartilhadas, que could ser uma concern for optimization.
  • O combination de singleton: true e strictVersion: true settings instructs Webpack para lança uma runtime erro se there é uma versão mismatch entre o Shell e o micro-frontend(s). Changing strictVersion para false would instead result em uma runtime aviso.
  • O requiredVersion: 'auto' opção, fornecido pelo @angular-architects/module-federation plugin, automatically determines o versão de your package.json, helping para prevent versão-related issues.

Configuring o Remote

O Micro-frontend, também known as o Remote em Module Federation, has uma structure semelhante a uma standard Angular app. It has specific rotas no AppModule e uma FlightsModule for flight-related tasks. Este section explains como para smoothly carregue o FlightsModule no Shell (Host).

Rota Definition

Establish o basic rotas within o AppModule:

export const APP_ROUTES: Routes = [
     { path: '', component: HomeComponent, pathMatch: 'full'}
 ];

Este simple routing configuração navigates para uma HomeComponent quando a aplicação é accessed.

Módulo Creation

Crie uma FlightsModule para tratar flight-related operations:

@NgModule({
   imports: [
     CommonModule,
     RouterModule.forChild(FLIGHTS_ROUTES)
   ],
   declarations: [
     FlightsSearchComponent
   ]
 })
 export class FlightsModule { }

Este módulo contains uma rota para uma FlightsSearchComponent defined as follows:

export const FLIGHTS_ROUTES: Routes = [
     {
       path: 'flights-search',
       component: FlightsSearchComponent
     }
 ];

Exposing Módulos via Webpack Configuração

To habilite o carregamento de FlightsModule no Shell, exponha it por meio do Remote's Webpack configuração:

const { shareAll, withModuleFederationPlugin } = require('@angular-architects/module-federation/webpack');

module.exports = withModuleFederationPlugin({
   name: 'mfe1',
   exposes: {
     './Module': './projects/mfe1/src/app/flights/flights.module.ts',
   },
   shared: {
     ...shareAll({ singleton: true, strictVersion: true, requiredVersion: 'auto' }),
   },
});

In este configuração:

  • O name propriedade identifies o micro-frontend as mfe1.
  • O exposes propriedade signifies o exposure de FlightsModule under o public name Module, allowing its consumption pelo Shell.
  • O shared propriedade lists o libraries para ser shared com o Shell, usando o shareAll método para compartilhar all dependências encontrada em your package.json. O singleton: true e strictVersion: true propriedades ensure esse uma single versão de shared libraries é usado, e uma runtime erro é triggered em case de versão incompatibility, respectively.

Starting o Aplicações

Having definir up o Shell (Host) e Micro-frontend (Remote), it's time para test o configuração para garantir o seamless integração de Module Federation.

To começa o Shell e Micro-frontend, use o seguintes comandos:

ng serve shell -o
ng serve mfe1 -o

Navigate para o Flights section no Shell para see o Micro-frontend being dinamicamente carregado.

Tip

O plugin installs um npm script run:all during o ng-add e init schematics, allowing for simultaneous serving de all aplicações:

npm run run:all
# or
npm run run:all shell mfe1

Optimizing Dependência Compartilhamento

O initial configuração com shareAll é simple e functional, but ele pode result no criação de unnecessarily large shared bundles.

To manage dependências compartilhadas mais effectively, consider switching de shareAll para usando o share helper. Este fornece finer control over que dependências são shared:

// Replace shareAll with share:
const { share, withModuleFederationPlugin } = require('@angular-architects/module-federation/webpack');

module.exports = withModuleFederationPlugin({
    // Specify the packages to share:
    shared: share({
        "@angular/core": { singleton: true, strictVersion: true, requiredVersion: 'auto' },
        "@angular/common": { singleton: true, strictVersion: true, requiredVersion: 'auto' },
        "@angular/common/http": { singleton: true, strictVersion: true, requiredVersion: 'auto' },
        "@angular/router": { singleton: true, strictVersion: true, requiredVersion: 'auto' },
    })
});

In este configuração, o share helper allows for explicit compartilhamento de selected pacotes, enabling uma mais optimized bundle compartilhamento e potentially reducing carregue times.