问题描述
我对自定义元素非常陌生。我需要创建一个自定义元素以集成到我们公司的另一个应用程序中。问题是我的自定义元素应该是我认为的默认导出。我需要让主机加载时以某种方式可以通过module.default
访问由angular创建的自定义元素。
有2个应用程序: HOST应用程序和 MY应用程序。 我无法更改主机应用。主机应用完全不在我的控制范围内。 主机应用是React应用。
主机应用执行以下操作:
<script type="module">
import('/my-angular-bundle.js')
.then(module => window.customElements.define('unique-custom-element-name',module.default))
.catch(error => console.error(error))
</script>
...
<unique-custom-element-name some-attribute='1' other-attribute='2'>
</unique-custom-element-name>
重要提示:我无法更改主机应用。主机应用程序具有其他这样加载的应用程序。脚本的加载方式无法更改。我需要找到一种方法来使生成的角度束与此加载方法一起使用。
我的角度应用程序是标准的angular-cli应用程序,除了:
- 我没有引导AppModule中的组件。我只是创建一个自定义元素并注册它。
- 要创建单个捆绑包,我使用了ngx-build-plus。实际上创建了2个文件:main.js和polyfills.js。我使用concat-glob-cli来连接两个文件。
- 在index.html中,我只包含了自定义元素
在我的应用程序中,app.module如下所示:
@NgModule({
declarations: [
SomeOtherComponent,AppComponent
],entryComponents: [
AppComponent
],imports: [
browserModule,],providers: [],})
export class AppModule {
constructor(private injector: Injector) { }
ngdobootstrap() : void {
const customElement = createCustomElement(AppComponent,{ injector: this.injector });
//*** how do I export customElement here?? ***
// I define the element here **JUST** to test it locally
customElements.define('app-root',customElement);
}
}
当我自己从index.html托管它时,这非常有效:
<body>
<app-root some-attribute='value'></app-root>
<script src="micro-frontend.js"></script>
</body>
但我必须像这样加载它,以便与已经投入生产且无法更改的HOST应用兼容。
<script type="module">
import('/my-angular-bundle.js')
.then(module => window.customElements.define('unique-custom-element-name',module.default))
.catch(error => console.error(error))
</script>
但是我不知道如何在我们的主机应用程序中使用它。因为主机应用程序尝试加载默认导出,并尝试使用默认导出define
自定义元素。我没有,因为我不知道如何进行默认导出。任何帮助表示赞赏。
使用的教程:
https://www.angulararchitects.io/aktuelles/angular-elements-part-i/
https://www.youtube.com/watch?v=E9i3YBFxSSE
解决方法
尝试托管在构建后获得的自定义元素js,并将该路径包含在托管的应用程序中。