As you probably know, Angular comes with a functionality that allows you to lazy load routable modules out of the box. Although in most cases this functionality is sufficient, it’s still only a small piece of the pie. What about situations where we want to lazy load modules that aren’t routable?

We can study one real-world case like this from our application. We have a page that displays a list of widgets. Each widget comes with a settings button that, when clicked, opens a side panel and allows the user to customize the widget’ settings.

The widget settings panel contains a world of components, directives, pipes, and providers. It would be a waste to add the module to our main bundle, because then all clients would have to download and parse it, even though most would probably never use it.

A better decision would be to lazy load the module when the user clicks on the edit settings button.

Let’s learn how can we do that.

First, we need to create the module:

We created a WidgetSettingsModule and provided it with everything it needs (i.e., components, directives, etc.).

Our next step is to instruct Angular to ask Webpack to create a separate chunk for our module so we can lazy load it later on. We can do this by adding the module path to the angular.json file:

Great, now we can see that Webpack extracts our module, with all of its dependencies, to a separate chunk.