Angular 使用 Angular 元素创建的 Web 组件覆盖了 Angular Shell 项目的应用根目录

Angular Web-Component created with Angular Elements overrides app-root of the Angular Shell Project

我目前正在试用 Angular Elements 来创建网络组件。我创建了一个在 html 页面中工作的网络组件:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Test</title>
</head>
<body>
<nav-bar title="Test"></nav-bar>
<script type="text/javascript"
        src="https://dev-week-web-components.s3.eu-central-1.amazonaws.com/nav-bar.js"></script>
</body>
</html>

web组件显示正确,title属性设置。

一旦我将 Web 组件嵌入到 Angular 应用程序中,应用程序根组件就不再有效。应用程序根组件始终为空,即使它有内容!如果我删除用于加载我的 Web 组件的脚本标签,shell 项目的应用程序根组件将再次运行。

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>NgElementsShell</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <script type="text/javascript"
          src="https://dev-week-web-components.s3.eu-central-1.amazonaws.com/nav-bar.js"></script>
</head>
<body>
<nav-bar></nav-bar> 
<app-root></app-root> <!-- Always empty! -->
</body>
</html>

要创建 Web 组件,我遵循了本教程:https://medium.com/comsystoreply/angular-elements-569025b65c69(仅限德语​​)。

使用 Angular Elements 创建的 Web 组件是另一个 Angular 项目的应用程序组件。

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

  ngDoBootstrap() {
    if (!customElements.get('nav-bar')) {
      const navBarElement = createCustomElement(AppComponent, {injector: this.injector});
      customElements.define('nav-bar', navBarElement);
    }
  }
}

Web 组件的 Angular 项目只包含这个组件:

@Component({
  // tslint:disable-next-line:component-selector
  selector: 'nav-bar',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
  encapsulation: ViewEncapsulation.ShadowDom
})
export class AppComponent implements OnInit {
  @Input() title = 'Web-Component';

  constructor() { }

  ngOnInit(): void {
  }
}

nav-bar.js 文件是 main.js、polyfill.js runtime.js 和 vendor.js 的合并文件,来自内置的 Angular 应用程序.在教程中,使用了 scripts.js 文件。我没有这个文件。如果我遗漏 vendor.js 文件,Web 组件将无法工作。

我做错了什么?

感谢user14649759的指点,才得以解决问题! :)

必须使用 Webpack 5。为此,我进行了以下更改:

npm install -g yarn@latest
yarn add webpack@latest
yarn add copy-webpack-plugin@latest

添加到package.json:

  "resolutions": {
    "webpack": "^5.31.0"
  },

告诉Angular使用纱线:

ng config cli.packageManager yarn

由于yarn使用了resolutions规范,所以yarn的使用是必要的。

来源:

https://www.angulararchitects.io/aktuelles/the-microfrontend-revolution-part-2-module-federation-with-angular/

https://github.com/jhipster/generator-jhipster/issues/13642