Angular 框架中
項目結構
main-app/src/app/app.module.tsapp.component.ts
micro-app/src/app/app.module.tsapp.component.ts
主應用配置
安裝必要依賴:
ng add @angular-architects/module-federation
修改 webpack.config.js
:
const { share, SharedMappings } = require('@angular-architects/module-federation/webpack');module.exports = {output: {uniqueName: "mainApp",publicPath: "auto"},optimization: {runtimeChunk: false},plugins: [new ModuleFederationPlugin({remotes: {"micro-app": "micro-app@http://localhost:4201/remoteEntry.js"},shared: share({"@angular/core": { singleton: true, strictVersion: true },"@angular/common": { singleton: true, strictVersion: true },"@angular/router": { singleton: true, strictVersion: true }})})]
};
主應用路由配置 (app.module.ts
):
const routes: Routes = [{path: 'micro-app',loadChildren: () => import('micro-app/MicroModule').then(m => m.MicroModule)}
];
子應用配置
子應用 webpack.config.js
:
const { share, SharedMappings } = require('@angular-architects/module-federation/webpack');module.exports = {output: {uniqueName: "microApp",publicPath: "auto"},optimization: {runtimeChunk: false},plugins: [new ModuleFederationPlugin({name: "micro-app",filename: "remoteEntry.js",exposes: {'./MicroModule': './src/app/micro.module.ts'},shared: share({"@angular/core": { singleton: true, strictVersion: true },"@angular/common": { singleton: true, strictVersion: true },"@angular/router": { singleton: true, strictVersion: true }})})]
};
子應用模塊 (micro.module.ts
):
@NgModule({declarations: [MicroComponent],imports: [CommonModule,RouterModule.forChild([{ path: '', component: MicroComponent }])]
})
export class MicroModule { }
運行應用
- 啟動子應用:
ng serve micro-app --port 4201
- 啟動主應用:
ng serve main-app --port 4200
訪問主應用路由 /micro-app
即可加載子應用模塊。
共享服務示例:
假如想要創建host和remote項目共享的部分,我們可以使用共享服務。
創建共享服務 (shared-lib.service.ts
):
@Injectable({ providedIn: 'root' })
export class SharedLibService {public data$ = new BehaviorSubject<string>('Initial Value');
}
在雙方應用的 webpack.config.js
中共享:
shared: share({"shared-lib": { singleton: true, strictVersion: true }
})
動態加載組件
????????有個時候我們在host項目中,想要通過非常規的模式使用remote中的頁面(常規方式是指官方指導文件中提到的方式,即路由方式),我們還可以怎么辦呢?
在主應用中動態加載子應用組件:
@Component({...})
export class HostComponent implements OnInit {constructor(private viewContainerRef: ViewContainerRef) {}async ngOnInit() {const m = await import('micro-app/Component');this.viewContainerRef.createComponent(m.MyExposedComponent);}
}
記得確保子應用暴露組件:
exposes: {'./Component': './src/app/my-component.ts'
}
詳細的各種方式可以參考下面這位大大的github:
倉庫地址:https://github.com/edumserrano/webpack-module-federation-with-angulargithub.com
React 框架中:
????????因為本人目前只比較熟悉Angular框架,所以關于React,各位可以參考下面這位大大的github:
GitHub - module-federation/module-federation-examples: Implementation examples of module federation , by the creators of module federation
?