Angular Micro Frontend ด้วย Module Federation

#angular12 เม.ย. 2569

Micro Frontend คืออะไร

Micro Frontend คือการแบ่ง frontend app ใหญ่ออกเป็น app เล็กๆ หลายอัน แต่ละทีมดูแล app ของตัวเองได้อิสระ

Module Federation กับ Angular

ใช้ Webpack Module Federation ผ่าน @angular-architects/module-federation

npm install @angular-architects/module-federation
ng add @angular-architects/module-federation --project shell --port 4200 --type host
ng add @angular-architects/module-federation --project mfe1 --port 4201 --type remote

Remote App (mfe1)

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

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

Shell App (Host)

// app.routes.ts
export const routes: Routes = [
  {
    path: 'flights',
    loadComponent: () =>
      loadRemoteModule({
        type: 'module',
        remoteEntry: 'http://localhost:4201/remoteEntry.js',
        exposedModule: './Component'
      }).then(m => m.FlightsComponent)
  }
];

Native Federation (ไม่ต้องใช้ Webpack)

npm install @angular-architects/native-federation
// federation.config.js (remote)
const { withNativeFederation, shareAll } = require('@angular-architects/native-federation/config');

module.exports = withNativeFederation({
  name: 'mfe1',
  exposes: {
    './routes': './src/app/app.routes.ts'
  },
  shared: { ...shareAll() }
});

ข้อดีและข้อเสีย

หัวข้อ ข้อดี ข้อเสีย
Team autonomy แต่ละทีมอิสระ ต้องประสานงาน
Deploy Deploy แยกกันได้ ซับซ้อนขึ้น
Bundle โหลดเฉพาะที่ใช้ Overhead

สรุป

Micro Frontend เหมาะกับ enterprise app ขนาดใหญ่ที่มีหลายทีม ถ้า app เล็กไม่จำเป็นต้องใช้ครับ