Angular 12中,模块联邦已经加入正式版。要在项目中使用模块联邦,需要在项目根目录下安装@angular-architects/module-federation库。然后在项目的webpack配置文件中进行以下配置。
const ModuleFederationPlugin = require('webpack/lib/container/ModuleFederationPlugin');
new ModuleFederationPlugin({ name: 'shell', remotes: {}, shared: {} })
name:该项目的名称,用于区分各模块
remotes:远程模块的配置信息
shared:相同依赖的配置信息
例如,假设我们在项目中引入了@my-org/shared-utils库,并且这个库在多个子项目中也被引用。这时可以设置shared配置,以保证这个库只会被加载一次,而不是被每个子项目都加载一遍。
new ModuleFederationPlugin({ name: 'shell', remotes: {}, shared: { '@my-org/shared-utils': {singleton: true} } })
在远程模块的配置中,可以通过指定模块所在的URL和模块的名称来引用远程模块。
new ModuleFederationPlugin({ name: 'shell', remotes: { 'my-remote-module': 'my-remote-module@http://localhost:5000/remoteEntry.js' }, shared: {} })
这时就可以在Angular应用中正常使用远程模块的组件和服务了。