4

Angular 2 document states "Shared features modules must be imported by any module expecting to use it's declarables".

I wonder why is it must to import Shared features module in to root module. Does it increase code base complexity?

Muhammad Faizan Uddin
  • 1,339
  • 12
  • 29
Albert
  • 94
  • 7

2 Answers2

2

Modules do not inherit each other, so even though the CharactersModule is going to be imported by the AppModule (which imports the SharedModule already), the CharactersModule cannot access the shared features, unless we import SharedModule. Here SharedModule is a different module and CharactersModule is a different module and we wanted to use SharedModule in the AppModule and CharactersModule so we need to import SharedModule in both.

Peter David Carter
  • 2,548
  • 8
  • 25
  • 44
Devansh
  • 1,277
  • 1
  • 13
  • 19
2

Modules are a way to declare stuff in angular, it defines what is needed by this logical block and what is exported by it. If you don't import your SharedModule in your RootModule, the components/services/pipes/etc defined in this SharedModule won't be available. For example, if you want to be able to use some built-in directives (ngIf,ngFor,etc...), you need to import CommonModule (or BrowserModule).

Let's say your SharedModule defines a component: AwesomeComponent with awesome as selector. If you want to be able to use this component in your RootModule (and why wouldn't you, it is awesome ?), you need to import the module that declares it, otherwise angular will complain (or fail silently) that it doesn't know this <awesome> tag.

Declaring multiple Modules can be useful if you want to isolate stuff, it enables you to make standalone library/part of application that you can reuse. If you make a new application and realize that awesome component you developped weeks ago would perfectly fit in it, if it has its own module you just need to import it.

It also allows easier bundling. instead of including that SharedModule in every lazy-loaded modules (lazy-loaded routes requires separate modules), you bundle it /load it once for all.

So does it increase code-complexity? yes, a bit, but it has many advantages.

n00dl3
  • 21,213
  • 7
  • 66
  • 76