Angular6でWebComponents入門

Blog Single

先日のAngular6リリースに伴って追加された@angular/elementsを使用し、WebComponents作成していきます。

 

1. Angularのプロジェクトを作成する

angular cliのインストール及びプロジェクトの作成を行います。


> npm i -g @angular/cli > ng new fh-components --prefix fh

2. @angular/elementsを追加する

ng add コマンドから追加することで、使用するための依存関係やファイルを作成してくれます。


> ng add @angular/elements info Direct dependencies └─ @angular/elements@6.0.9 info All dependencies └─ @angular/elements@6.0.9 ✨ Done in 5.57s. Installed packages for tooling via yarn. Added `document-register-element` as a dependency. Added document-register-element.js polyfill to scripts UPDATE package.json (1395 bytes) UPDATE angular.json (3756 bytes)

3. コンポーネントを作成する

インラインオプションとspecファイルなしを付与し、コンポーネントを生成します。


> ng g component button --inline-style --inline-template --spec false

生成されたコンポーネントを編集し、以下のようにしました。

4. CustomElementを作成する

@angular/elementsのcreateCustomElement関数を使用して、ブラウザネイティブのcustomElements.define機能で使用できるインスタンスを作成していきます。

また、entryComponentsにButtonComponentを登録することでAppModule内でButtonComponentを使用することが出来るようになります。

app.module.tsはこのようになりました。

これでWebComponentsのソースコードができました、次はビルドして実際に使ってみます

5. 実際に使ってみる

今回サーバを建てるのはhttp-serverを使います


npm i -D http-server

tsconfig.jsonのtargetを編集します。

"target": "es2015"

package.jsonのscriptsへビルドとパッケージング、サーバ立ち上げの3つのスクリプトを追加します。

"build": "ng build --prod --output-hashing=none"
"package": "cat dist/fh-components/{runtime,polyfills,scripts,main}.js | gzip > fh-components.js.gz"
"serve": "http-server --gzip"

プロジェクトルートにindex.htmlを作成します。

あとはコマンドを打ち込むだけです


> npm run build > npm run package > npm run serve

立ち上がったサーバにアクセスします、デフォルトでhttp://127.0.0.1:8080に立ち上がるようです。

アクセスするとfh-componentが動作することがわかります。

まとめ

思っていたよりも手軽にAngularの記法を用いてWebComponentsを作成することができました。

jsファイルを読み込むだけであらゆる場所で使えるコンポーネントというのは大きな魅力で、各ブラウザのWebComponents対応が進んでいけば、WebComponentsを用いた開発も近い将来実用的になっていくような気がしました。

参考: “Building Custom Elements/Web Components with Angular 6” by @sulco

Posted by MachidaMamoru
typescriptとAngularが好き、最近Dapps開発にハマっています。

Other Posts: