AOT Packaging, Lazy Loading Failure

· 2 min read

Problem

When developing with Angular, as features continuously get added, modules and components increase, causing the overall size to grow. This increases the time required for users’ initial loading, degrading the experience. Angular’s solution to this is lazy loading.

In theory: in lazy loading mode, after packaging, JS will be split into multiple chunks, allowing users to load resources as needed when navigating routes.

However, when I performed AOT packaging, I found that the lazy loading files did not appear. Instead, main.js was quite large. Upon opening the file and searching for keywords, I discovered that the logic that should have been lazy loaded was still inside. This made it clear that lazy loading had failed. When trying JIT, I found that lazy loading worked properly.

This led me to suspect that it was likely an issue with the build tool version. The version with the packaging issue was:

"@ngtools/webpack": "1.2.3",

Solution

Upgrade the version to 1.3.1 Perform AOT packaging again, and it works, as shown:

ng-bundle

Notes

  • Since AOT packaging is memory-intensive, if you encounter memory overflow errors during the build process, increase the memory allocation. Learn how to do this here
  • The version doesn’t necessarily need to be the latest, as versions have dependencies and relationships. Consider your actual situation and requirements. For example, my current Angular version is 4.0.1. By checking the official changelog, I know it was released on 2017-03-29. Correspondingly, @ngtools/webpack 1.3.1 was released on 2017-04-25T02:55:41.698Z, so I chose this version.
  • For actual web deployment, it’s recommended to enable GZIP, which will reduce the browser loading size by at least half, making loading faster.