如何用Webpack或Angular CLI将Angular Element编译为Web Component?
问题:本地打包Angular Elements为独立Web Component文件
我跟着Pascal Precht的教程用Angular构建了一个简单的Web Component,在Stackblitz上能自动编译正常运行,但本地环境就是搞不定。
我的最终目标是:在本地把生成的Web Component代码打包成单个独立文件,之后我可以把它上传到服务器,然后像使用原生HTML/JavaScript Web Component那样,只用一个<script>标签就能引入使用。
详情
我的代码结构很简单,核心是一个基础组件和对应的模块:
HelloComponent 组件代码
import { Component } from '@angular/core'; @Component({ selector: 'hello-world', template: `<h1>Hello world</h1>` }) export class HelloComponent {}
AppModule 模块代码
import { NgModule, Injector } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { createCustomElement } from '@angular/elements' import { HelloComponent } from './hello.component'; @NgModule({ imports: [BrowserModule], declarations: [HelloComponent], entryComponents: [HelloComponent] }) export class AppModule { constructor(private injector: Injector) {} ngDoBootstrap() { const HelloElement = createCustomElement(HelloComponent, { injector: this.injector }); customElements.define('hello-world', HelloElement); } }
关于这个模块的几个关键处理:
- 将组件添加到
entryComponents数组,避免被Angular的摇树优化移除(因为应用启动时不会直接访问到它):entryComponents: [HelloComponent] - 调用
createCustomElement函数,把Angular组件转换成可作为常规HTML Web Component使用的元素:const HelloElement = createCustomElement(HelloComponent, { injector: this.injector }); - 最后在
main.ts中启动Angular编译该组件:platformBrowserDynamic().bootstrapModule(AppModule);
我已尝试的资源
我已经翻遍了不少资料,包括但不限于:
- 《Web Components from Scratch》(作者Tomek Sułkowski)—— 没有涉及单独打包的内容
- 《Web Components with CLI》(作者Tomek Sułkowski)—— 同样没解决我的问题
- Academind的Web Components教程视频—— 只讲解了在Angular应用内部使用的场景
实在卡在这里了,有没有大佬能指导一下怎么在本地实现把Angular Elements打包成单个独立文件?
内容的提问来源于stack exchange,提问作者VSO
相关产品推荐
相关产品推荐

