Ideal size of shared module(s) in Angular

1.8k Views Asked by At

I have an Angular project with several feature modules but I'm not sure what's the best practice for structuring shared modules.

  1. Is it considered best to have one large SharedModule imported in each feature module even if it contains components, pipes, directives, etc. that are used only in a few but not all feature modules?
  2. Or is it better to split them up into smaller modules (logical units) and import them one by one to feature modules only where they're needed?

I think that (1) sounds a lot easier to write but I'm somewhat concerned that importing partly unused code into each feature module may slow down my application and make lazy-loading somewhat pointless. If somebody can shed light on the advantages and disadvantages of both strategies, that would be very welcome. Thanks!

2

There are 2 best solutions below

0
On

It depends on your app needs of course. I'd personally create several shared Modules depending on your other modules needs.

Imagine the following example :

  • I have 2 features modules that need a specific custom table.
  • I have 3 features modules that use flex-layout and only one of the 2 features modules that use a custom table use flex-layout.

This is a typical example where you will have one big shared module that imports and exports everything, but in that case the 3 features modules will import the table classes while they don't use it.

In this case I find it useful to split the shared module into several that correspond to my needs. Usually, that means I'll create a StyleSharedModule, a TableSharedModule, etc...

Anyhow, the size is not an important factor. You could have a really light shared module with a lot of sub-modules, and you could also have a really heavy shared module which only import a few things (but big things).

To me, the logical needs is the important things that makes you create different shared modules, not the size.

0
On

From the several past projects than I have created, I can tell that you have more than one way to go.

Though, if you want to use Ahead of time compilation and lazy loading, you should do differents modules, out of the shared. Use Shared just for the reusable components (components used more than once) and all generic component, ex: a chart component visible on several pages (i-e: several modules) The content of the shared will be loaded a the start of the app so it must not be to large.

If it's a small project, with no lazy loading, I don't see the goal to put a lot of component inside the shared module.