Working with Angular on real life projects, I have developed my own set of patterns for organising scalable Angular code on large and complex apps. I thought it would be useful to share them.

I tried to separate them in small articles, and to be as concise and clear as possible.

Other articles in the series:

Lazy loaded modules

In my mind, I always divide the project I am working on in a set of pages grouped inside different lazy loaded modules.

I think this mental structure comes from my background in Ruby on Rails, where there is an analogous division of actions grouped inside different controllers. The two concepts are very different, but the analogy stands, because it’s always beneficial to categorise what you have to do in a high-level list of items, each containing a sublist.

To decide your lazy loaded modules structure, the first thing you have to do is look at the requirements, and write down clearly all the different urls that get accessed during the user journey. Url = page = a situation in which, if the user refreshes the browser, he gets back to the very same HTML he is looking at.

When you have the full list of pages, you need to group them in different lazy loaded modules, trying to optimise the amount of shared dependencies among them. Shared dependencies = reusable components that you put in your boilerplate.

If two pages depend on a very similar set of reusable components, put them together in the same lazy loaded module.

Grouping pages this way is very good for performance, because you minimise the amount of lazy loaded modules that depend on the same reusable component.

Let’s say that page P1 depends on reusable components A, B, C, and page P2 depends on A, B, D. If you put P1 and P2 in two different lazy loaded modules, each of them has a copy of A and B, so, for each, the final bundle is potentially bigger than it could be.

Of course, don’t get paranoid about this, there are cases in which you cannot avoid a component to be repeated in two different modules. You have to consider also that tools like WebPack are becoming really sophisticated in optimising bundles, so you can always rely on packaging for production being lighter than for development. So, it’s just a good rule of thumb, if you start optimisation since the beginning it will be easier to maintain when the application grows.