0
1

More than 5 years have passed since last update.

angular.io FUNDAMENTALS/Bootstrapping メモ

Posted at

Bootstrap

アプリケーションは少なくとも1つのModuleを持っていて、 bootstrap でアプリケーションを起動する。便宜的にAppModuleと呼ぶ。

src/app/app.module.ts
import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent }  from './app.component';

@NgModule({
  imports:      [ BrowserModule ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

bootstrap で指定したコンポーネントが index.html に描画される。

The imports array

Angularでは機能ごとのモジュールを統合してアプリケーションを作る。Angular自体も、 HttpModule RouterModule のようにモジュールに分かれている。 imports の配列にモジュールを追加してそのモジュールの機能を使う。

ほとんどのアプリケーションがブラウザで動作するので、 @angular/platform-browserBrowserModule が必要になる。

imports に入るのは NgModule のクラスだけで、他のクラスを入れてはいけない

ES2015の import とAngularのNgModuleでの imports は異なる

The declarations array

モジュールで使うコンポーネント、ディレクティブ、パイプを全て declarations に並べる。 declarations に入れていないコンポーネントを使うとエラーメッセージがブラウザに表示される。

declarations に入れるのはコンポーネント、ディレクティブ、パイプのみで他のNgModuleクラスやサービスクラスなどを入れてはいけない

The bootstrap array

AppModuleをbootstrapしてアプリケーションを起動する。 bootstrap の配列に並べたコンポーネントがDOMに挿入される。

各ブートストラップされたコンポーネントはコンポーネントのツリーのルートになる。

複数のコンポーネントを bootstrap に書くのは一般的ではなく、ほとんどの場合一つのコンポーネントを指定し、それがルートコンポーネントとなってコンポーネントのツリーとなる。

そのルートのコンポーネントをなんと読んでもいいが、大抵のデベロッパーは AppComponent と呼ぶ。

Bootstrap in main.ts

アプリケーションをブートストラップする方法はたくさんある。どれにするかは、コンパイルの方法と実行の方法による。

最初はアプリケーションを動的にコンパイルするJIT(Just-In-Time)コンパイラを使って、ブラウザ上でコンパイルする。他の方法は後述する。

JITコンパイルのアプリケーションは src/main.ts に置くのを勧める。

src/main.ts
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule }              from './app/app.module';

platformBrowserDynamic().bootstrapModule(AppModule);

このコードは、動的(JIT)コンパイル用のブラウザプラットフォームを作成し、上記のAppModuleをブートストラップする。

ブートストラップは実行環境を設定し、モジュールの bootstrap 配列からルートになる AppComponent を取り出し、コンポーネントのインスタンスを生成してタグを挿入する。

setup/src/index.html
<my-app><!-- content managed by Angular --></my-app>

More about Angular Modules

最初のアプリではルートのモジュール一つだけだが、アプリケーションが大きくなるとフィーチャーモジュールに切り分けて遅延ロードすることもできる。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1