我正在使用 Angular 11 和 Webpack 5 开发一个新项目。我的工作基于 Manfred Steyer 的Module Federation Plugin Example repo,它使用 Angular CLI。我不知道如何在我的两个应用程序之间从共享的本地 Angular 库中共享单例服务。
我会尽力解释我的设置。真的很抱歉这会持续多久。
简化的文件结构
root
package.json
projects/
shell/
src/app/
app.module.ts
app.component.ts
webpack.config.ts <-- partial config
mfe1/
src/app/
app.module.ts
app.component.ts
webpack.config.ts <-- partial config
shared/
src/lib/
global.service.ts
package.json <-- package.json for lib
角
两个 app.component.ts 文件是相同的
import {GlobalService} from 'shared';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
constructor(shared: SharedService) {}
}
全球服务.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class GlobalService {
constructor() {
console.log('constructed SharedService');
}
}
网页包
外壳/webpack.config.ts
const ModuleFederationPlugin = require("webpack/lib/container/ModuleFederationPlugin");
module.exports = {
output: {
publicPath: "http://localhost:5000/",
uniqueName: "shell"
},
optimization: {
// Only needed to bypass a temporary bug
runtimeChunk: false
},
plugins: [
new ModuleFederationPlugin({
remotes: {
'mfe1': "mfe1@http://localhost:3000/remoteEntry.js"
},
shared: ["@angular/core", "@angular/common", "@angular/router"]
})
],
};
mfe1/webpack.config.ts
const ModuleFederationPlugin = require("webpack/lib/container/ModuleFederationPlugin");
module.exports = {
output: {
publicPath: "http://localhost:3000/",
uniqueName: "mfe1"
},
optimization: {
// Only needed to bypass a temporary bug
runtimeChunk: false
},
plugins: [
new ModuleFederationPlugin({
// For remotes (please adjust)
name: "mfe1",
library: {type: "var", name: "mfe1"},
filename: "remoteEntry.js",
exposes: {
'./Module': './projects/mfe1/src/app/app.module.ts',
},
shared: ["@angular/core", "@angular/common", "@angular/router"]
})
],
};
共享库 package.json
{
"name": "shared",
"version": "0.0.1",
"main": "src/public-api.ts",
"peerDependencies": {
"@angular/common": "^11.0.0-next.5",
"@angular/core": "^11.0.0-next.5"
},
"dependencies": {
"tslib": "^2.0.0"
}
}
此配置编译并运行,但mfe1
实例化一个新的GlobalService
. 我在应用程序加载时看到“构造的 SharedService”,然后在加载远程模块后再次看到。我试图遵循ScriptedAlchemy 的另一个示例,但我不知道如何使其工作。它要么编译并运行并创建两个实例,要么无法编译引用缺少的模块,这取决于我确定我的配置是如何搞砸的。
ScriptedAlchemy 示例使我似乎需要shared
在文件的库数组中引用我的共享库webpack.config.ts
。这完全有道理,但我无法让它工作
shell/webpack.config.ts and mfe1/webpack.config.ts
...
shared: ["@angular/core", "@angular/common", "@angular/router", "shared"]
如果我以这种方式引用本地库,我不可避免地会在构建过程中出现错误
Error: Module not found: Error: Can't resolve 'shared' in '/Path/to/module-federation-plugin-example/projects/shell/src/app'
我发布的示例已简化。希望不要过分如此,但这里是一个显示问题的回购链接