How we got 70% decrease in Angular bundle size

Alexandr Ursu
3 min readDec 3, 2020

My experience to optimize Angular bundle size and project loading time.

When I just started working at my current job I had a chance to inherit a huge monolith Angular project and first thing that caught my attention was loading time, it took about 1 minute for project to be loaded. I decided to “inspect” the code with Chrome DevTools where I found this nice surprise:

My reaction was like. No way! 99.9 MB I saw for the first time in my life such a big number in a web project. It was a good starting point to familiarize with current project.

  1. Build the project in production mode ng build --prod

Wait, that’s basics. Of course, but I found out that project was always deployed in development mode. Once I tried to build the project with --prod flag I got ~1000 TSLint errors, now I knew what was preventing developers from doing that. That actually was first step of project cleanup and optimization. After one week of cleaning up TypeScript errors I was able to build project in production mode and my effort was rewarded bundle size went from 99.9 MB => 29.5 MB

2. Update to the latest version of Angular

Since we were using Angular 6 we decided to update it to the latest version of Angular 9. Don’t even ask how we did that, it was long painful process and Angular Update Guide was very helpful. Ivy compiler was promising as per Angular Blog:

Small apps could see around a 30% decrease in bundle size, large apps will see a 25–40% decrease, and medium apps decrease minimally. Source: Angular Blog

This didn’t help a lot I guess we saw about 0.5MB bundle size decreasing, still a progress.

3. Check project Imports — tree shakeable imports

Make sure your 3rd party dependencies are tree shakeable. Don’t import entire modules like @angular/core, but just the submodules that are required. Some examples:

// Bad 
import npmModule from "npm-module";
// Bad
import 'rxjs';
// Good
import { export1 , export2 } from "npm-module";

Frankly we got stuck here, it is a big work ahead. Once finished I will update the post with the results.

— — —

I will keep updating this post with the idea to create definitive guide for Angular bundle optimization, so, if you have some ideas or came across some beautiful solutions please leave a comment below.

--

--