@angular/Elements

介绍

在Angular v6中添加了一个特性,Angular Elements又称angular元素

@angular/Elements是Angular中的一个新包,它帮助我们将Angular组件发布自定义元素。它基于浏览器的 Custom Elements API 实现,通过将Angular组件转化成web Components来做到这一点。让我们来看看如何合理利用这一特性。


作用&好处

使用Angular元素,我们可以使我们的组件真正地可重用。也就是说,我们可以在其他架和库中使用Angular组件,比如ReactVueEmber!也可以在angularjs中使用angular/Elements
还可以把Angular添加到项目后端,好处多多啊🤙


项目创建

确保Angular CLI版本 大于v6,因为v6才开始支持@angular/Elements的。

创建一个angular的基础项目

1
2
3
ng new angular-app
cd angular-app
ng serve --open

接着创建一个angular组件

1
ng g c HelloWorld

安装@angular/elements

1
2
ng add @angular/elements
ng add @webcomponents/webcomponentsjs

安装好之后,转到app.module。,并对@NgModule进行以下更改:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, Injector } from '@angular/core';
import { createCustomElement } from '@angular/elements';

import { HelloWorldComponent } from './hello-world/hello-world.component';

@NgModule({
declarations: [HelloWorldComponent],
imports: [BrowserModule],
entryComponents: [HelloWorldComponent],
providers: [],
})
export class AppModule {
constructor(injector: Injector) {
const custom = createCustomElement(HelloWorldComponent, { injector });
customElements.define('app-hello-world', custom);
}

ngDoBootstrap() { }
}


创建一个独立的元素

如果一个项目有N个组件,要从中抽取一个转换成WebComponents,打包的时候救需要把这个组件单独打包,否则文件会比单个组件包大。这里建议创建一个独立的元素(或者该项目全是webComponents

在Angular项目的根目录中创建一个名为preview的新文件夹。在这个文件夹中,创建一个名为index.html的新文件,并在其中编写以下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<script src="./angularapp.js"></script>
</head>

<body>
<app-hello-world></app-hello-world>
</body>

</html>

现在我们不再需要AppComponent了,可以删除没有用的文件:
app.component.css
app.component.html
app.component.spec.ts
app.component.ts
app.routing.module.ts,之需保留app.module


打包&运行

在项目根目录添加一个custombuild.sh的Shell的脚本文件

1
2
#!/bin/sh
ng build angular-app --prod --output-hashing=none && cat dist/angular-app/{runtime,polyfills,scripts,main}****.js > preview/angularapp.js

shell脚本不支持Bash,所以加了 #!/bin/sh,用git-bash运行。

这里打包有很多方式,可以用gzip压缩体积,其他脚本库,还有Angular v7 更新的Ivy,Angular v9都出了🚀

这里的打包比较简陋,实质就是把ng build的生成文件合并到了angularapp.js。运行这个脚本,preview会多出一个angularapp.js文件

最后一步,在根目录运行

1
npx live-server preview

页面显示’hello-world works!’如果可以那个恭喜创建成功了🎉
此外你可以去其他尝试引用angularapp.js,并用<app-hello-world></app-hello-world>元素。


总结

这篇文章主要记录了,Angular如何利用@Angular/Elements将angular组件转换成webComponent。
很简单对吧233。

上文提到@Angular/Elements是基于浏览器Web Components的Custom Elements API实现的,Web Components还有其他API Shadow DOMHTML templates详细可以参考 跳转 Angular Elements将Custom Elements的API实现了抽象化,因此代码会更优雅,可读性和维护性也更好,同时也更易于扩展。

关于@Angular/Elements的打包,本文方法比较粗劣。后期考虑使用工具打包压缩,提高页面js请求效率。

学无止境,还得辛苦加油!🤣

推荐