将完整的 Angular 应用程序转换为 WebComponent

问题描述 投票:0回答:1

我有一个完整的 Angular 16 应用程序,包含路由、多个组件和服务,我需要将其转换为单个 Web 组件,可以通过外部 UI 应用程序/shell 中的

script
标签加载。

到目前为止,我遇到的所有教程和资源都演示了使用 Angular Elements 将单个组件 Angular 应用程序转换为 Web 组件,例如此示例 -

import { Injector, NgModule } from '@angular/core';
import  { createCustomElement } from '@angular/elements';
import {HttpClientModule} from "@angular/common/http";
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing. Module';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home. Component';

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent, HomeComponent]
})
export class AppModule {

  constructor(private injector: Injector) {
    const el = createCustomElement(HomeComponent, {injector: this. Injector});
    customElements.define('element-home', el);
  }

  ngDoBootstrap() {}
 }

在这里,我的 Angular 应用程序中有一个名为

HomeComponent
的组件,我可以从中创建一个名为
<element-home>
的 Web 组件。例如,可以通过这种方式将其加载到 HTML 页面中 -

<body>
  <element-home></element-home>
  <script src="...." /> // bundled Angular javascript files
</body>

但是,如何将完整的 Angular 应用程序(带有路由)转换为 Web 组件?我的角度组件结构看起来像这样 -

- AppComponent
  <router-outlet> 
  |
   - HomeComponent // for /home route
   - DetailComponent // for /detail route
   - DetailService

此外,有关此主题的任何教程/资源/指南将不胜感激!

javascript angular typescript web-component
1个回答
0
投票

因此,如果您使用 Angular 16,您可以使用独立 API(请参阅底部的 stackblitz 链接):

警告应用程序不应包含任何延迟加载的部分

当您在存储库中构建该应用程序时,您将获得三个 js 文件:

  1. 运行时.js
  2. polyfills.js
  3. main.js

您必须将它们连接到一个文件中,并保持上述顺序。 这样,您将获得一个包含新 Web 组件的 js 文件。

import { Component, ViewEncapsulation } from '@angular/core';
import { createCustomElement } from '@angular/elements';
import { createApplication } from '@angular/platform-browser';
import 'zone.js';

@Component({
  selector: 'app-home-component',
  standalone: true,
  template: `
    <h1 class="my-class">Hello from {{ name }}!</h1>
  `,
  styles: `
    .my-class {
      color: green;
    }
  `,
  encapsulation: ViewEncapsulation.ShadowDom,
})
export class HomeComponent {
  name = 'HomeComponent';
}

async function webComponentApp() {
  const app = await createApplication({ providers: [] });
  const element = createCustomElement(HomeComponent, {
    injector: app.injector,
  });
  customElements.define('home-app', element);
}

(async function () {
  await webComponentApp();
})();

Stackblitz 示例

© www.soinside.com 2019 - 2024. All rights reserved.