AngularCLIで単一ファイルコンポーネント
AngluarCLIでComponentを作成する際にVue.jsの単一ファイルコンポーネントっぽく、1Component1ファイルとする方法を紹介します。
やってみる
コマンド実行時のオプションで指定
コンポーネント作成(デフォルト)
$ ng g c <コンポーネント名>
$ ng g c --inline-style --inline-template <コンポーネント名>
--inline-style
--inline-template
オプションを付けて実行することでcss、htmlの内容がtsファイルにインラインで記述されます。
※ gはgenerateのエイリアス
※ cはcomponentのエイリアス
.angular-cli.jsonに設定を記述
事前にプロジェクトの設定ファイルに記述しておく方法です。
... "defaults": { "styleExt": "css", "class": { "spec": false }, "component": {} } }
.angular-cli.json(単一ファイルコンポーネント)
... "defaults": { "styleExt": "css", "class": { "spec": false }, "component": { "inlineStyle": true, "inlineTemplate": true } } }
以上です。
確認
オプション指定、もしくは.angular-cli.jsonに設定を記述した状態でComponentを作成してみます。
作成されたコンポーネントを確認すると、一つのtsファイルにstyleとテンプレートがまとまっているのが分かるかと思います。
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-one-file', template: ` <p> one-file works! </p> `, styles: [] }) export class OneFileComponent implements OnInit { constructor() { } ngOnInit() { } }
参考
https://github.com/angular/angular-cli/wiki/generate-component