微前端 - 已创建具有不同配置的平台。请先销毁它

Micro Frontend - A platform with a different configuration has been created. Please destroy it first

我正在尝试使用 Angular 和 Webpack 模块联合为微前端构建 POC。 在此,我创建了一个 shell 应用程序和另一个 mfe1 应用程序,并在特定路线上渲染该 mfe1 命中,它按预期工作并渲染应用程序。现在,我正在尝试创建另一个名为 mfe2 的应用程序并进行渲染。在此 mfe2 中,我正在使用 Angular 元素创建一个 Web 组件并在 shell 应用程序中呈现它。当我这样做时,我面临以下问题

Error: A platform with a different configuration has been created. Please destroy it first.

执行以下代码时

import('mfe2/web-component')
    .then(_ => console.debug(`element loaded!`))
    .catch(err => console.error(`error loading `, err));

我不明白具体问题出在哪里。我在下面添加所需的代码。

MFE2:

app.module.ts

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: []
})
export class AppModule {
  constructor(private injector: Injector) {}

  ngDoBootstrap() {
    const ce = createCustomElement(AppComponent, {injector: this.injector});
    customElements.define('mfe2-elem', ce);
  }

}

webpack.config.js

module.exports = {
  output: {
    uniqueName: "mfe2",
    publicPath: "auto"
  },
  optimization: {
    runtimeChunk: false
  },   
  resolve: {
    alias: {
      ...sharedMappings.getAliases(),
    }
  },
  plugins: [
    new ModuleFederationPlugin({
      
        // For remotes (please adjust)
        name: "mfe2",
        filename: "remoteEntry.js",
        exposes: {
          './web-component': './src/bootstrap.ts',
        },        
        
        // For hosts (please adjust)
        // remotes: {
        //     "mfe1": "mfe1@http://localhost:3000/remoteEntry.js",

        // },

        shared: {
          "@angular/core": { singleton: true, strictVersion: true }, 
          "@angular/common": { singleton: true, strictVersion: true }, 
          "@angular/common/http": { singleton: true, strictVersion: true }, 
          "@angular/router": { singleton: true, strictVersion: true },

          ...sharedMappings.getDescriptors()
        }
        
    }),
    sharedMappings.getPlugin()
  ],
};

SHELL:

在组件中渲染它:

@Component({
  selector: 'app-mfe2element',
  templateUrl: './mfe2element.component.html',
  styleUrls: ['./mfe2element.component.scss']
})
export class Mfe2elementComponent implements AfterContentInit {

  @ViewChild('vc', { read: ElementRef, static: true })
  vc!: ElementRef;

  constructor() { }

  ngAfterContentInit(): void {
    import('mfe2/web-component')
    .then(_ => console.debug(`element loaded!`))
    .catch(err => console.error(`error loading `, err));

    // await import('mfe1/web-components');
    // const element = document.createElement('mfe1-element');
    // document.body.appendChild(element);

    const element = document.createElement('mfe2-elem');
    this.vc.nativeElement.appendChild(element);

  }

}

webpack.config.js

module.exports = {
  output: {
    uniqueName: "shell"
  },
  optimization: {
    // Only needed to bypass a temporary bug
    runtimeChunk: false
  },
  plugins: [
    new ModuleFederationPlugin({
        // For remotes (please adjust)
        // name: "shell",
        // filename: "remoteEntry.js",
        // exposes: {
        //     './Component': './/src/app/app.component.ts',
        // },        
        
        // For hosts (please adjust)
        remotes: {
            "mfe1": "mfe1@http://localhost:3000/remoteEntry.js",
            "mfe2": "mfe2@http://localhost:4000/remoteEntry.js",
        },

        shared: {
          "@angular/core": { singleton: true, strictVersion: false }, 
          "@angular/common": { singleton: true, strictVersion: false }, 
          "@angular/router": { singleton: true, strictVersion: false },

          ...sharedMappings.getDescriptors()
        }
        
    }),
    sharedMappings.getPlugin(),
  ],
};

请帮我解决这个问题。

谢谢...

从这里获取解决方案: https://github.com/angular-architects/module-federation-plugin/issues/47#issuecomment-845145887

每个共享 Angular 版本,我们只能创建一个平台。要记住我们的版本已经有一个共享平台,我们可以将它放入一个将版本号映射到平台实例的全局字典中:

const ngVersion = require('../package.json').dependencies['@angular/core']; // better just take the major version 

(window as any).plattform = (window as any).plattform || {};
let platform = (window as any).plattform[ngVersion];
if (!platform) {
  platform = platformBrowser();
  (window as any).plattform[ngVersion] = platform; 
}
platform.bootstrapModule(AppModule)
  .catch(err => console.error(err));

将此添加到 shell 和 mfe 中的 bootstrap.ts 将使 mfe 重用现有平台而不是尝试创建新实例,这将导致错误正在经历。