既存のAngularプロジェクトにAngular Elementsを導入する


はじめに

メモ書き程度。
Github pageで使うように出力先は docs になっているので注意。

プロジェクトにAngular Elements用のモジュールを生成する

ng g module custom-element/custom-element

生成されたmoduleを以下のように変更

custom-element.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

@NgModule({
  declarations: [],
  imports: [
    BrowserModule,
  ],
  entryComponents: []
})

export class CustomElementModule {}

Moduleにカスタムエレメントにするコンポーネントの作成

ng g component custom-Element/hoge-fuga/hoge-fuga -v Native

先程作成した custom-element.module.tsentryComponents に作成したコンポーネントを追加し、カスタムエレメントのセレクターを追加する。

custom-element.module.ts
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を作成する。

tsconfig.element.json
{
  "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 に以下を追加する。

angular.json
"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"
        }
      ]
    }
  }
}

普通のビルド設定と変わらないので適宜変更する。

ビルド用のコマンドを追加する

package.json
...
scripts: {
  ...
  "build:element": "ng run プロジェクト名:element:production --output-hashing=none && cat docs/elements/{runtime,polyfills,main}.js > docs/elements/hoge-element.js"
}
...

使い方

何かしら.html
<body>
  <app-hoge-fuga></app-hoge-fuga>
  <script src="hoge-element.js"></script>
</body>

参考

https://mae.chab.in/archives/60134
https://winsmarts.com/getting-started-with-angular-elements-1bbdf2e748a6