The Accidental Import That Taught Me to Love Angular Budgets
Funny thing happened to me with one of my angular apps that I decided to share. Angular apps have this concept of “size budget” that you can set in the build configuration. The way it works is that once budget configuration is in place, building your app can generate a warning or fail with an error if the output bundle exceeds a certain size.
I was working on an older app with no budget warning/errors set and just by accident noticed that the size of my app bundle was over 5MBs! Even compressed down to 2 MBs that’s an annoying hit for the user to take to load my app. What the hell, what’s going on, why is it so big? I could remember it being somewhere in 400KB range in size before.
What happened? While I was working on some feature, I accidentally triggered an import via auto-complete that imported typescript library into my app. Here is what undoing the damage looked like in the git commit:
I honestly don’t even know what I was doing to get this to happen, but I definitely didn’t type this one out and I might have just triggered an auto-complete accidentally, then missed it during the commit reviews. From that point on, this typescript library was bundled with my Angular app, blowing its size up.
I removed the offending lines of code and my builds went back to <1MB in size. Build size budget limits is a perfect defense mechanism against issues like this. You can add the budget configuration to your angular.json config file for the build task. Here is what I added to my app:
"configurations": {
"production": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
"budgets": [
{
"type": "initial",
"maximumWarning": "500kB",
"maximumError": "1.0MB"
},
{
"type": "anyComponentStyle",
"maximumWarning": "2kB",
"maximumError": "4kB"
}
],
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"namedChunks": false,
"aot": true,
"extractLicenses": true
}
It can alert you when the app size increases, and if it’s not something you expected to happen — you can take a look and hopefully catch the culprit and fix it before it goes out to prod and slows things down.