This article will give you a better understanding of how Angular split your code into chunks.
If you are scared from Angular CLI output showed above or if you’re curious how that code-splitting actually happens then this post is for you.
Code splitting allows you to split your code into various bundles which can then be loaded on demand. If used correctly, can have a major impact on load time.
Let’s imagine you started a brand new Angular project. You read many resources on how to architect an Angular application, what is the appropriate folder structure and, what is most important, how to keep great startup performance.
You chose Angular CLI and created a modular application with lots of lazy-loaded feature modules. And of course, you created a shared module where you put commonly used directives, pipes, and components.
After a while, you caught yourself thinking that once your new feature module requires some functionality from other feature modules you tend to move this functionality to that single shared module.
The application evolves and soon you noticed that its startup time doesn’t meet your(and, most importantly, your client) expectation.
Now, you’re in doubts…
Let’s demystify!
As we all know, the current Angular CLI version uses webpack to perform bundling. But despite that, webpack is also responsible for code-splitting.
So, let’s take a look at how webpack does it.
Webpack 4 introduced SplitChunksPlugin that allows us to define some heuristics to split modules into chunks. Many people complain that this configuration seems mysterious. And at the same time, this is the most interesting part of code splitting.
But before SplitChunksPlugin optimization is applied webpack creates a new chunk:
Angular CLI configures the following entry pointsmain
polyfills
styles
which will result in the chunks with the same names.
[**import()**](https://webpack.js.org/api/module-methods/#import-1)
syntax that conforms to the ECMAScript proposal for dynamic imports)Do you remember loadChildren syntax? This is the signal for webpack to create a chunk.
Now let’s move on to the SplitChunksPlugin. It can be enabled inside optimization
block of webpack.config.js
Let’s look at Angular CLI source code and find that configuration section:
#angular #performance #webpack