Optimize Angular Build Size | webpack bundle analyzer

A big sized javascript bundle is never good for the user experience. A major problem being the download time as it increases the wait time for the application to get ready.

The thing is, it’s easier than ever to add third party modules and tools to our projects, but this can come with a huge performance tradeoff.

When the project is big then it becomes even more difficult to analyze the bundle (which is also having many third part libraries) and further optimize it.

This article will help to understand how can we used webpack bundle analyzer with Angular to visualize which code is coming from where.

Let’s setup one angular project, adding third part library and use webpack bundle analyzer to visualize the bundle and reduce the bundle size

# Create a new Angular project
$ ng new DemoProject
$ cd DemoProject
$ npm i devextreme@20.1.7 devextreme-angular@20.1.7 --save

open app.module.ts file and add DxDataGridModule module. Below is code to add DxDataGridModule module.

# Generate prod build
$ npm run build

After execution of above you will notice that dist folder gets created and its size is around 45 MBs.

Let’s install the webpack-bundle-analyzer plugin:

$ npm i webpack-bundle-analyzer -save-dev

The Angular CLI gives us the ability to build with a stats.json out of the box. This allows us to pass this to our bundle analyzer and start the process.

We can add a new script to package.json to add this functionality:

"scripts": {
"build:stats": "ng build --stats-json"
}

Now we can run npm run build:stats to generate a stats.json file inside of the dist folder! Let’s do that:

$ npm run build:stats

We can make another script which runs the webpack-bundle-analyzer with the stats.json:

"scripts": {
"analyze": "webpack-bundle-analyzer dist/DemoProject/stats.json"
}

Run the analyzer with the following command:

$ npm run analyze

You should then be able to see your analysis over at localhost:8888:

In the above picture, we can easily see that the third party libraries (devextreme & devextreme-angular) are fully imported means all the modules (grid/forms/router etc.)of these libraries are imported and are the part of prod bundle but we only wanted to use grid module.

That means we are missing something and which is also causing decent increase in prod bundle size.

Improvement here is very simple, instead of importing all modules for devextreme, we should only import grid module.

# Generate prod build
$ npm run build

Now check the size of dist folder, its now decreased to 20 MBs.

That means by only changing the grid module import path, the bundle size is reduced from 45 MBs to 20 MBs.

So we are able to reduce bundle size by 55% which is a huge achievement.

Great!

Coder