Angular Budgets: Keeping Your Application Performant and Responsive

ahmoustafa35

Ahmed Moustafa

Posted on May 17, 2023

Angular Budgets: Keeping Your Application Performant and Responsive

Get ready to dive into the wacky world of Angular budgets! In this hilariously informative blog post, we'll be exploring the budgetary roller coaster that awaits every Angular developer. From the penny-pinching 'bundle' budget to the resource-hungry 'maximum' budget, we'll unravel the mysteries behind each budget type. Hold onto your funny bones as we navigate through budget limitations, busting them wide open with clever tricks and tips. It's time to turn those budget blues into budget LOLs as we embark on this comedy-filled adventure into the realm of Angular budgets!

Angular: More Than Just Geometry, It's the Hipster's Choice for Web Apps!

Angular, the superstar of web development, has stolen the hearts of developers worldwide with its ability to build fancy web applications. But hey, as these apps grow bigger and more complicated, they can start acting like divas, causing sluggish response times and giving users a "meh" experience. Imagine waiting forever for a website to load - it's like watching paint dry, but way less exciting!

Why The Need for Speed?

Research shows that people have the patience of a goldfish when waiting for websites to load. They want it fast, like flash-fast! Slow-loading sites are a recipe for disaster, causing users to throw tantrums and abandon ship faster than you can say "JavaScript." So, to keep users engaged and prevent them from unleashing their inner Hulk, it's crucial to turbocharge your Angular applications for speed and performance.

Show Me the Money

Enter the superhero called Angular Budgets! They're like those strict teachers who keep things in check. These budgets allow developers to set limits for different aspects of their app, such as size, performance, and responsiveness. Think of it as setting boundaries for your code, like a parent telling their kids, "No, you can't have ten extra scoops of ice cream!"

One major culprit for slow websites is those chunky JavaScript bundles. With Angular budgets, you can put them on a diet! Developers can monitor and control the size of these bundles, preventing them from getting bloated and slowing down the app. It's like keeping your app on a treadmill, ensuring it stays fit and fast!

But wait, there's more! Angular budgets also act as a superhero sidekick for preventing performance issues. As your app grows and evolves, it may gain a few extra pounds, affecting its performance. With Angular budgets, you can be like a detective, constantly tracking your app's size and performance metrics. If it starts acting up, you'll catch it red-handed and take the necessary measures to whip it back into shape.

But how to know my current bundle size?

To determine your current bundle size in an Angular application, you only need to build your Angular application.



ng build 
or 
ng build --prod


Enter fullscreen mode Exit fullscreen mode

And here you go, a nice table that contains our bundles.

Our App Size

It's time to dive into the wild and wacky world of bundle files! We all know that understanding these bundles is the secret sauce to optimizing our app's performance, and it's like cracking a code that unlocks the magical powers of speed and efficiency.

Like a Box of Chocolates, Except They're Bundles!

  • Main Chunk:
    The granddaddy of them all! This chunk holds the fundamental logic and functionality of our app, and it's like the boss who decides how the initial view gets rendered. But fear not; we have tricks up our sleeves like lazy loading and code splitting to make this chunk lean and mean. Say goodbye to sluggish loading times!

  • Polyfills Chunk:
    The superhero of old browsers! This chunk swoops in during the production build to ensure compatibility with those ancient browser beasts. It's like a bridge that fills the gaps in browser capabilities, making our app work seamlessly across different environments. No browser left behind!

  • Runtime Chunk:
    The master of ceremonies at runtime! This chunk plays a critical role in bootstrapping and initializing our app, and it's like the glue that holds all the other code together. To boost performance, we can slice and dice this chunk into smaller, bite-sized pieces. Think of it as serving an app buffet with manageable portions. Yum!

  • Styles Chunk:
    The fashionista of our app! This chunk gathers all the CSS styles used in our Angular masterpiece. It's the second-largest file in the production build, but no worries, we have style optimization tricks up our sleeves. We'll shake those trees and purge unused styles, making this chunk slimmer than a supermodel on a diet. Hello, fast loading times!
    So, fellow developers, armed with the knowledge of these quirky chunks and their sizes, we can work our magic. It's time to optimize our Angular app and achieve performance greatness! But wait, there's more! We have a secret weapon called webpack-bundle-analyzer. This tool lets us visualize our bundle sizes in a way that would make even Picasso jealous. We'll unravel the mysteries behind our bundle composition and unlock valuable insights. Get ready to analyze like never before!

Budgets Under the Microscope

Now, let the bundle bonanza begin as we embark on an epic journey of optimizing our Angular bundle sizes. Together, we'll create a performance masterpiece that will make users go, "Wow!" So, strap on your developer capes and let's rock those bundles!

To utilize webpack-bundle-analyzer effectively, we need to begin by installing it. Follow these steps to incorporate this tool into your Angular project:

  • Open your terminal or command prompt and navigate to your project's root directory.

  • Execute the following command to install webpack-bundle-analyzer as a development dependency:



npm install --save-dev webpack-bundle-analyzer


Enter fullscreen mode Exit fullscreen mode
  • Then we can run another build with a flag —stats-json


ng build --stats-json 
or 
ng build --prod --stats-json


Enter fullscreen mode Exit fullscreen mode
  • After running this command a cool file will be generated in the dist folder called stats.json this file contains the data for all the dependencies that are being used by our application. To visualize it we can run this command.


webpack-bundle-analyzer ./dist/${project-name}/stats.json


Enter fullscreen mode Exit fullscreen mode

And voila you will see this nice view of our project bundles.

Initial Application Size

Alrighty, let's dive into the bundle fun! Check it out, my friends. The main bundle is strutting its stuff at a whopping 237.46 kb, with a crew of 91 cool modules. Now, picture this: our talented developer decides to add some pizzazz to our app with the one and only Angular Material. They go all out and bring in the MatBadgeModule and the MatDatepickerModule. Oh yeah, our app is dressed to impress!

But how will our stats look like? Let's run the build again and check how it looks like.

Here we added some dependencies

Now, let's take a look at our main bundle. It has grown to a size of 318 kb, accompanied by a team of 134 modules. Don't worry, though - we're still within acceptable limits, and all these modules are being put to good use. We're keeping things balanced and staying on track with our budgets.

But hey, hold on to your hats, because there's a twist in our story! Our design got a makeover, and our clever developer decided to swap out the date picker for a simple text box. The MatFormFieldModule came into the picture to add some flair to our new text box. However, in the rush of excitement, our developer forgot to remove the MatDatepickerModule from our app.module imports. Oops, we all make mistakes!

Opps we forgot something

So, let's take a closer look at our stats and see what happened. As we dig into the numbers we found that we are at 397 kb, we might notice a little surprise waiting for us. Ah, there it is! The MatDatepickerModule, still hanging out in our imports, even though it's no longer partying in our HTML. It's like an eager guest who missed the memo that the date picker moved out of the app. Let's give it a gentle reminder to find its way back home.

Making Your App Run Faster Than a Caffeine-Infused Unicorn!

Alright, let's stop here and approach this bundle situation with a relaxed vibe. It's time to do some detective work and figure out why this is happening and how we can solve it. We all know that projects can vary in size, and sometimes it feels like making the main bundle smaller is as tricky as finding a unicorn in the wild. But worry not, my friends, because we've got some handy solutions up our sleeves.

First up, we've got code splitting. It's like breaking our code into bite-sized pieces, making it more digestible. By doing this, we can keep our main bundle in check and improve its performance. It's like serving smaller portions of code goodness.
Next, let's give a shout-out to tree-shaking. No, it's not about violently shaking trees (although that would be quite the spectacle). It's about shaking off any unnecessary code branches, like shedding those extra layers in winter. We want our bundle to be lean and efficient, so we'll get rid of anything that's not pulling its weight.
Now, it's time to optimize our dependencies. Think of it as a mini makeover for our code. We'll tidy things up, make sure our dependencies are playing nicely together, and trim any excess baggage. It's like decluttering our code closet.
And guess what? We've got a superhero called the bundler optimizer. It swoops in to save the day, making our bundle shine brighter than a disco ball. This magical tool knows all the tricks to optimize our code and make it perform like a rockstar. It's like having a secret weapon in our coding arsenal.
Last but not least, let's talk about minimizing those Angular polyfills. They're like the support crew for older browsers, ensuring our app can strut its stuff across different platforms. But hey, let's keep them light and nimble, just enough to get the job done without stealing the spotlight.
Now that we've got a handle on budgets, bundles, and sizes, let's ease into the world of configuration. It's time to adjust the settings and find that sweet spot for our projects. So grab a cup of your favorite beverage, put on some relaxing tunes, and let's dive into the art of configuration. It's all about finding that perfect harmony between our code and the magic that makes it run smoothly. Let's do this with a chilled-out mindset!

Now How can I change the budget limits for my project?

To configure angular budgets you need to open the angular.json file of your project.



"architect": {
        
"build": {
          "configurations": {
            "production": {
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "500kb",
                  "maximumError": "1mb"
                },
                {
                  "type": "anyComponentStyle",
                  "maximumWarning": "2kb",
                  "maximumError": "4kb"
                }
              ],
            },
    }
}


Enter fullscreen mode Exit fullscreen mode

Alright, fellow adventurer! Let's dive into the marvelous world of Angular budgets and unravel the mysteries of different budget types. It's like exploring a treasure trove filled with exciting size measurements that'll make your coding heart flutter with joy.

The Wild Variety Show of Angular's Budget Types!

  • bundle: It's like putting a size tag on a specific bundle, so you know exactly how big it is. It's like giving each bundle its own fashionable outfit and making sure it fits just right..

  • Initial: Think of it as the VIP of sizes, representing the js file that's essential for bootstrapping your application. It's the star of the show, the one that gets everything started. Make sure it's not too big, or else your app might take longer to get off the ground..

  • allScript: the size of all your application scripts combined. It's like a scrumptious buffet of code, where you can keep an eye on the total size of your script feast. Watch out for any code gluttony!

  • all: the size of your entire application. It's like weighing your app on a cosmic scale and seeing how it measures up. Keep an eye on this one to make sure your app doesn't become too heavy to handle.

  • anyComponentStyle: It's the size of any component's stylesheet, like a fashionista's wardrobe. Make sure those styles are looking fabulous without weighing down your app.

  • anyScript: It's like a wildcard, capturing the size of any of your precious scripts. It's like herding all the code cats and keeping them in check.

  • any: the size of any file that tickles your coding fancy. It's like a magical size measurement that can apply to anything you desire. Keep an eye on this one if you want to monitor the sizes of all things great and small.

With these marvelous budget types, you have the power to track and control the sizes of anything your heart desires. Set your desired sizes for the warning and error cases, like setting the boundaries for your code playground. It's like being a size superhero, ensuring your app stays in tip-top shape. So go forth, my friend, and conquer those budgets with a sprinkle of coding magic!

💖 💪 🙅 🚩
ahmoustafa35
Ahmed Moustafa

Posted on May 17, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related