LoginSignup
47
39

More than 5 years have passed since last update.

Angularの declarations, imports, providers の使い分け

Posted at

こんにちわ。はこです。
Angularを書くときに最初にこのように書きますね。

@NgModule({
    // なんやかや〜〜〜
    declarations: [AppComponent],
    imports: [BrowserModule],
    providers: [MyService],
    bootstrap: [AppComponent]
})
class AppModule {
}

あるいは、テストを書くときに、以下のように書きますね。

describe('MyGreatComponentのテスト', () => {
  let component;
  let fixture;

  // テスト準備
  beforeEach(async(() => {
    // テストベッド(テスト環境)構築
    TestBed.configureTestingModule({
      // なんやかや〜〜〜
      declarations: [ MyGreatComponent ],
      imports: [  ],
      providers: [  ]
    })
    .compileComponents();
  }));

  // テストコード
  it('isGreat() は常にtrueを返すこと。なぜならGreatだから', () => {
    expect(component.isGreat()).toBeTruthy();
  });
});

この「なんやかや〜〜〜」の部分は、どのように使い分ければよいのでしょうか。

実は簡単な使い分け

  • declarations : ディレクティブ(含コンポーネント、パイプ)を書きます。 htmlテンプレートに書くもの、ですね。
  • providers : Serviceなど、DIで解決するものをここに書きます
  • imports : 外部のAngularモジュール。Httpモジュールとか、UIモジュールとか。

これだけです!

AppModuleの設定ではあまり悩まなくても、テストベッドの依存性解決では間違いやすそうですので注意したいですね!

その他、あまり使わない/設定変えないもの

  • exports : モジュール作者向け。外部公開する対象を指定。
  • bootstrap : 起動コンポーネント。 AppComponentを渡せばだいたい大丈夫
  • entryComponents : テンプレート中で使ってない(<app-my-great>等の記述がない)コンポーネントを登録しとく
  • schemas : 「Angular以外のカスタムエレメントのスキーマ指定」らしい…。おそらくAngular以外(ReactやVue.js)と共存するための機構。 いまのところNO_ERRORS_SCHEMACUSTOM_ELEMENTS_SCHEMAが指定できて、前者はあらゆるパターン、後者だと <my-react-component>等のハイフン区切りが許可されるみたい。
47
39
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
47
39