Reducing Bundle size in angular2

Generally when we create any project in angular6 , the overall bundle size that gets loaded is big. So, the more the 3rd party js library we will use the more the size of bundle there will be. So as the bundle size increases the the loading time for our application gets increased.

Here I have made a new angular6 application. Also I have installed angular material + ng-bootstrap.I am running it through ng serve

 Let us see the output :

chunk {main} main.js, (main) 11.7 kB [initial] [rendered]

chunk {polyfills} polyfills.js, (polyfills) 227 kB [initial] [rendered]

chunk {runtime} runtime.js, (runtime) 5.22 kB [entry] [rendered]

chunk {styles} styles.js, (styles) 15.6 kB [initial] [rendered]

chunk {vendor} vendor.js, (vendor) 6.5 MB [initial] [rendered]

ℹ 「wdm」: Compiled successfully.


Note : Here i have installed the Angular material+ng-bootstrap/ Because of which the size has been increased to 6.5 mb

1)One way to reduce the size of vendor.js is ng serve –prod.

Note : In –prod automatically the AOT (Ahed of time) compilation will take place

chunk {main} main.js, (main) 10.4 kB [initial] [rendered]

chunk {polyfills} polyfills.js, (polyfills) 227 kB [initial] [rendered]

chunk {runtime} runtime.js, (runtime) 5.22 kB [entry] [rendered]

chunk {styles} styles.js, (styles) 15.6 kB [initial] [rendered]

chunk {vendor} vendor.js, (vendor) 6.17 MB [initial] [rendered]

After the command a new build folder named dist gets created. So, we have reduced the size of vendor.js from 6.5 mb to 6.17 mb

2)Now , to track which file is consuming what size, let us install source-map-explorer

what is source-map ?

The source map explorer determines which file each byte in your minified code came from. It shows you a treemap visualization to help you debug where all the code is coming from. 

npm install -g  source-map-explorer

After installation , go to the dist folder and then type :

source-map-explorer vendor.js

Note : We can see the total size is 6.4 mb. Here @angular in itself is consuming 4.6 mb.

That is really large consumption.

No, let us compress these little more..

Let us now, go to the deployment documentation of angularJs. Here we can see the AOT compilation. When we use ng build –prod. It will use AOT compilation. Now through this the size will be reduced significantly.Let us run this

ng build –prod

chunk {0} runtime.a66f828dca56eeb90e02.js (runtime) 1.05 kB [entry] [rendered]

chunk {1} styles.34c57ab7888ec1573f9c.css (styles) 0 bytes [initial] [rendered]

chunk {2} polyfills.2f4a59095805af02bd79.js (polyfills) 59.6 kB [initial] [rendered]

chunk {3} main.0cfde28f7f0cc84a3ce8.js (main) 349 kB [initial] [rendered]


In angular6 they have removed the vendor.js during –prod

source-map-explorer main.js


Again using the –dev and –aot the size gets reduced my folds.

Finally size gets reduced to 59.6 kB

By Pankaj Kumar Agarwal

Leave a reply:

Site Footer