In this section, we are going to see, how to dynamically import modules and other related components. In enterprise apps, there might be a scenario, where in you end up loading the modules based on some metadata, say which is coming from some REST call may be. In those scenarios, this kind of implementation is needed. We will discuss Lazy Loading in detail when we talk about those scenarios. However, let’s look at the code where we lazy load modules with all its dependencies.
Note:- This is not normal lazy loading scenario, where in simply lazy load components by clicking on some route. This is the case where app.module.ts will have no idea, which module to load. Basically, its lazy loading modules and its related assets dynamically.
Here, we will be using webpack’s import feature to dynamically load module on demand.
Now, let’s understand the same step by step. Let’s see the structure of application. app.module.ts file looks like
Then, app.component.ts file like
Afterwards, my static component like
Lastly, app-routing.module.ts looks like
Therefore, these are pretty basic stuffs for any Angular App. Now, let’s see the dynamic part of this. Below, how my dynamic component looks like
Then, Dynamic Module
Finally, Dynamic routing module
Here, I have used, RouterModule.forChild as I have defined sub-routes here.With the above changes in place, when I build the app, it will throw me below error.
It says “Dynamic Import cannot be used when targeting ECMAScript 2015 modules“. And the reason for this, Dynamic Imports work only with future version ES. Hence, If I go to tsconfig.app.json which just extends tsconfig, we can see that module is pointing to es2015, which in case of dynamic imports won’t work.
Hence, we need to change module to esnext like shown below. This is very important. Hence, keep this point in mind.
With above changes in place, my app looks like
Now, look at the network tab.
This is the case of initial page load. Now, when I clear the traffic and click on any link say Load a dynamic Component, it will come like this.
And network tab looks like this. This means only required info loaded, basically required module loaded dynamically.
Similarly, when I click on Load Movies link, it will load movies and its related assets.
Again, I am repeating, don’t confuse Lazy loading modules with normal lazy loading in angular. Normal Lazy loading works just fine, without any module changes.
This is not normal lazy loading scenario, where in simply lazy load components by clicking on some route. This is the case where app.module.ts will have no idea, which module to load. Basically, its lazy loading modules and its related assets dynamically.
In coming section, we will see how to publish your project as core package as in NPM package and then install the same for building feature apps on top of Core SPA. Thanks for joining me.
Download Code:- https://github.com/rahulsahay19/angular-4-lazy-loading
8,573 total views, 5 views today