Implementare Micro Frontend con Angular 19 e Module Federation: Shell + Runtime Integration




Genera il progetto principale:

ng new shell-app --routing --style=scss
Enter fullscreen mode

Exit fullscreen mode



Aggiungi il supporto Module Federation:

ng add @angular-architects/module-federation --type host --port 4200
Enter fullscreen mode

Exit fullscreen mode



Esempio di configurazione webpack.config.js:

const ModuleFederationPlugin = require("webpack/lib/container/ModuleFederationPlugin");

module.exports = {
  output: {
    publicPath: "http://localhost:4200/",
    uniqueName: "shell"
  },
  optimization: {
    runtimeChunk: false
  },
  plugins: [
    new ModuleFederationPlugin({
      name: "shell",
      remotes: {
        mfeProduct: "mfeProduct@http://localhost:4201/remoteEntry.js",
        mfeProfile: "mfeProfile@http://localhost:4202/remoteEntry.js"
      },
      shared: {
        "@angular/core": { singleton: true, strictVersion: true },
        "@angular/common": { singleton: true, strictVersion: true },
        "@angular/router": { singleton: true, strictVersion: true }
      }
    })
  ]
};
Enter fullscreen mode

Exit fullscreen mode




Genera un’app remota:

ng new mfe-product --routing --style=scss
Enter fullscreen mode

Exit fullscreen mode



Configura webpack.config.js:

new ModuleFederationPlugin({
  name: "mfeProduct",
  filename: "remoteEntry.js",
  exposes: {
    "./ProductModule": "./src/app/product/product.module.ts"
  },
  shared: {
    "@angular/core": { singleton: true, strictVersion: true },
    "@angular/common": { singleton: true, strictVersion: true }
  }
});
Enter fullscreen mode

Exit fullscreen mode




Step 3: Caricamento Dinamico (Runtime Integration)

Usa il helper loadRemoteModule:

import { loadRemoteModule } from '@angular-architects/module-federation';

export const routes: Routes = [
  {
    path: 'product',
    loadChildren: () =>
      loadRemoteModule({
        remoteEntry: 'http://localhost:4201/remoteEntry.js',
        remoteName: 'mfeProduct',
        exposedModule: './ProductModule'
      }).then(m => m.ProductModule)
  }
];
Enter fullscreen mode

Exit fullscreen mode




Best Practice

  • Standalone Components: Angular 19 supporta componenti standalone, riducendo la complessità dei moduli.
  • Shared Dependencies: Usa singleton: true per Angular core/common/router.
  • Errori comuni: Evita di condividere Angular come peerDependency (può causare NG0200 Circular DI).
  • Nx Monorepo: Per team grandi, Nx semplifica la gestione di più MFE con caching e generators.



Conclusione

Con Angular 19 e Module Federation puoi creare architetture scalabili, modulari e indipendenti. Questo setup permette:

  • Deploy indipendenti.
  • Aggiornamenti rapidi.
  • Riduzione dei conflitti tra team.



Source link

Leave a Reply

Your email address will not be published. Required fields are marked *