In my new Fundamentals of Angular course that is being released later this week, I cover lazy loading with Angular feature modules. In the section on lazy loading, we encounter the import() function. One of the things that can be confusing about this function is how it compares to the more common import statement.
I've previously written about the import statement and how it can be confusing. If you want a deeper dive on that, check out my blog here.
Generally, the import statement looks something like this and appears at the top of our files:
But it doesn't allow us to either delay the inclusion of some code into our client-side project, or delay the download and loading of some of our code.
As projects get bigger and more complex and we use larger and larger frameworks and more and more third-party tools, our initial bundle can get unreasonably large. So finding the parts of our application that aren't needed initially, and downloading them later can improve the initial performance of our application. And if the code is never needed, then we don't have to force the user to download it.
This functionality is enabled with the import function.
The import function uses quite a different syntax than the static import statement.
It looks like this:
Let's go over this syntax, and what it's doing.
Once the module has been downloaded, you now have a handle to the module itself and can do whatever you want with it in the then callback function of the promise. Note that the downloaded module is immediately parsed and executed by the browser without you doing anything. So if the code has any side effects, you can't stop them from happening.
This is the mechanism used by many frameworks and libraries to download code on demand whenever needed.
We use XHR calls to gather data, but we use the dynamic import function to gather additional code our project may need.
The import function is used far less often than the static import statement, but it's still extremely useful to understand.
Signup for my newsletter here.