我已经阅读了其他答案,但没有成功地使用 Angular 13 实现联合模块。我总是收到“共享模块不可用于急切消费”消息。
主机应用程序 webpack.config.ts:TL;博士:
- 仔细检查自定义 webpack 配置中的公共路径 - 它可能缺少尾随的
,WebPack 可能会错误地报告为“无法急切使用”。/
- 检查路由 - 您的 MFE/远程模块将在主机模块的路由之后接收子路由(因此,如果您的主机在点击路由“登录”时路由到 MFE,则您的 MFE 将不会获得“登录” ' 路径,它将得到一个空路径(请参阅下面的更新 2)。
可能需要(也可能不需要)引导(下面的更新 1)。
export const webpackConfig: Configuration = {
output: {
publicPath: 'http://localhost:4200',
uniqueName: 'host',
},
plugins: {
new container.ModuleFederationPlugin({
name: "host",
remotes: {
"remote-login": "login@http://localhost:4201/remoteEntry.js"
}
shared: [
"@angular/core",
"@angular/common",
"@angular/router",
"@angular/common/http",
]
})
]
}
export default webpackConfig;
远程应用程序:
export const webpackConfig: Configuration = {
output: {
publicPath: 'http://localhost:4201',
},
optimization: { runtimeChunk: false },
experiments: { outputModule: true },
plugins: {
new container.ModuleFederationPlugin({
name: "login",
filename: "remoteEntry.js",
exposes: {
LoginComponent: './projects/module1/src/app/pages/login/login.component.ts',
},
shared: [
"@angular/core",
"@angular/common",
"@angular/router",
"@angular/common/http",
]
})
]
}
export default webpackConfig;
更新1:main.ts
文件中使用它:
import('bootstrap').catch(err => console.error(err))
现在可以在控制台中看到以下错误 - 该错误仅与新的引导进程相关:
ChunkLoadError: Loading chunk projects_host_src_bootstrap_ts failed.
_注意:此错误是因为 webpack.config.ts 中定义的公共路径缺少尾部斜杠。 引导它尝试从 http://localhost:4200projets_host_src_bootstrap_ts
加载块(缺少端口号后面的
/
)。更新2:
Error: ASSERTION ERROR: NgModule 'LoginComponent' is not a subtype of NgModuleType.
所以至少我又回到了“角度误差之地”。我必须将 LoginModule(LoginComponent 的主页)中的路由设置为:
export const routes: Routes = [
{
path: '', //Note: empty path, _not_ matching the app's 'login' path
loadChildren: () => import('./login/login.component').then(m => m.LoginComponent),
}
]
更新3:正在运行
export const routes: Routes = [
{
path: '', //Note: empty path, _not_ matching the app's 'login' path
component: LoginComponent,
}
]
我将回滚引导更改并查看是否需要它们,但现在至少使用联合模块!
Webpack 文档。
简而言之,您需要一个异步边界(由文件的存在创建bootstrap.js
+
index.js
),以确保在客户端加载时等待共享依赖项:
index.js
:
import('./bootstrap.js');
bootstrap.js
:
import React from 'react';
// ... the rest of application root component
您还可以将 eager: true
添加到共享依赖项,但这会将它们添加到初始块中,无论是否使用它们。
main.ts
内容移动到新文件
bootstrap.ts
并将
main.ts
更新为:
import('./bootstrap').catch((error) => console.error(error));
并且它正在工作!
ng serve --hmr
似乎是问题所在。删除热模块重新加载消除了错误。