将Angular Elements引入现有的Angular项目中
首先
只需要一种选项,用中文将以下内容进行释义:仅仅是一些随笔。请注意,输出的目标是为了在Github页面上使用,因此设定为”docs”文件夹。
生成适用于Angular Elements的模块以供项目使用。
ng g module custom-element/custom-element
将生成的模块按如下方式进行修改
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
@NgModule({
declarations: [],
imports: [
BrowserModule,
],
entryComponents: []
})
export class CustomElementModule {}
创建一个将模块化转为自定义元素的组件。
ng g component custom-Element/hoge-fuga/hoge-fuga -v Native
将新建的组件添加到之前创建的 custom-element.module.ts 文件的 entryComponents 中,并添加自定义元素的选择器。
import { createCustomElement } from '@angular/elements';
...
import { HogeFugaComponent } from './hoge-fuga/hoge-fuga.component'
...
export class CustomElementModule {
constructor(private injector: Injector) {
const element = createCustomElement(HogeFugaComponent, { injector });
customElements.define('app-hoge-fuga', element);
}
ngDoBootstrap() { }
}
为Angular Elements添加构建配置。
创建tsConfig文件。
{
"extends": "./tsconfig.base.json",
"compilerOptions": {
"outDir": "./out-tsc/app",
"types": []
},
"files": [
"src/app/custom-Element/custom-element.ts",
"src/polyfills.ts"
],
"include": [
"src/**/*.d.ts"
]
}
请在angular.json文件的projects > architect部分添加以下内容。
"element": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "docs/elements",
"main": "src/app/custom-Element/custom-element.ts",
"index": "src/index.html",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.element.json",
"aot": true,
"assets": [],
"styles": [
"src/styles.scss"
],
"scripts": []
},
"configurations": {
"production": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
"optimization": true,
"outputHashing": "none",
"sourceMap": false,
"extractCss": true,
"namedChunks": false,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true,
"budgets": [
{
"type": "initial",
"maximumWarning": "2mb",
"maximumError": "5mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "6kb",
"maximumError": "10kb"
}
]
}
}
}
由于与普通的构建设置没有区别,因此需要根据需要进行适当修改。
添加用于构建的命令
...
scripts: {
...
"build:element": "ng run プロジェクト名:element:production --output-hashing=none && cat docs/elements/{runtime,polyfills,main}.js > docs/elements/hoge-element.js"
}
...
使用方法
<body>
<app-hoge-fuga></app-hoge-fuga>
<script src="hoge-element.js"></script>
</body>
请提供下列的汉语本土化版本。
https://mae.chab.in/archives/60134的文章是关于Angular Elements的入门指南。
https://winsmarts.com/getting-started-with-angular-elements-1bbdf2e748a6是一篇关于如何开始使用Angular Elements的文章。