Core Module vs Shared Modules - Why, When, and Where 🤔
As developers, we love reusing and recyling DRY (Don’t Repeat Yourself) code. Where should we place this reusable code though? Should it be in the Shared Module, or the Core Module?
Let’s look at what each module is used for and determine simple rules on how to determine which module should this be placed into.
🧠 Core Module
This module should contain your services and components that you know should be a single instance in the app. The main thing about this module is that this is only imported once in the Root module (AppModule).
Should I put this here? 🤔
Since the Core module is only imported once, components and services here have to be a singleton, or only having a single instance. Therefore, it makes sense that things with a single state that need to be kept are placed here.
Things like:
- Feature Services
- Other services that should be loaded when the app starts.
- Components that will only have a single instance in the app (things like the navbar).
Tips 💡
Some people prefer to make the Core module purely made of services, with not declarations
, and that’s perfectly fine too. The important thing is to communicate conventions with the team to make sure you guys are on the same boat.
🎁 Shared Module
The Shared module on the other hand, unlike the Core module, is imported by all other feature modules as needed. Also, the components here aren’t singleton instances like in the Core module, you can have multiple instances of the components here.
Should I put this here? 🤔
The biggest difference between the two modules is that the Core module is imported only in the Root module while the Shared module can be imported in multiple modules. This means the components here don’t necessarily have to be singletons to placed here.
Put these in the Shared module:
- Components, Directives, and Pipes that you use everywhere in the app.
- You should almost never put services here - the only contents in your
providers
should be Pipes or Directives you directly inject into the app.
Tips 💡
You can re-export commonly imported modules here like the FormsModule
and the CommonModule
in the Shared module too!
🏁 Final Notes
Just like with most things in the real world, not everything is cut and dry and these rules aren’t set in stone. Deviate if you will, just make sure you communicate with your team and figure out what is best for your project.
Thanks for reading! 🥳