Angular AoT Compilation, Lazy Loading, and Treeshaking With Webpack
- If the file causes problems because of not finding any files it may be that the aot folder does not exist .
- After that output is created, you can go along and consume these files via webpack.
- We also have to tell webpack how to name the files which are recognized as lazy loaded.
- compile our files via the ngc compiler
- With the webpack uses our aot-file as an entry point and follows all imports in this file.
In this blog post, we’ll show you how to get Ahead of Time compilation enabled with lazy loading in combination with Webpack 2.
If you want to enable lazy loading in your application with AoT, you first have to configure your router to load the module lazy – when it gets requested. You can do that with the loadChildren-attribute.
If you did this you have to remove the module import from the module import array where you explicitly imported it in the first place!
If done so, you can install the necessary packages to get started with the ngc compiler:
After this, you have to configure a separate tsconfig-aot.json for Ahead of Time Compilation:
If you now run:
… an “aot” folder is created which should contain all of your compilated files.
Also, as an entry point, we specify the file(s) we have, but the main file is different. Because we created an output in the AoT folder, we need to point our entrypoint to that compilated files!
We can do that by adding a new main.ts file called “main-aot.ts” and add the following into it:
Here we are consuming the generated files in the AoT folder.
After that output is created, you can go along and consume these files via webpack.
which enables loading modules through the string we mentioned in the routes.
to proceed with our files.
The rule for this looks like the following:
… and as an entry point we are pointing to the new file we created:
With this webpack uses our aot-file as an entry point and follows all imports in this file.
We also have to tell webpack how to name the files which are recognized as lazy loaded. We can do this by adding a “chunkFilename” in the output-settings:
from webpack which we can configure like this:
Ahead of Time compilation and treeshaking are two different things often used together. AoT is done via a different compiler. Treeshaking can be done via webpack but also rollup.js is a way to go.
So we need to have two steps:
“scripts” section like this:
which you can run via
I hope I was able to clarify a bit about how AoT and treeshaking work with webpack 2 and Angular.