Three+ steps to minimize angular application size

On my daywork project come to the state when a size of compiled bundles dramatically increase and it becomes a problem.

Ok, I’ve installed Webpack bundle analyzer and tried to analyze what each bundle consists of.

In project already used lazy-loading modules, so already have several javascript chunk files. But we have an extremely large chunk for the common module. So I’ve paid much attention for this chunk and here what I found.

In this bundle, I’ve found a full library like angular-material instead of only used modules.

First step:

Use Lazy-loading and accurate distribute components between modules (NgModules), even there is only one component

Second step:

Maximize use of modularity for third-party libraries.

For example:
use

import {Observable} from 'rxjs/Observable';

instead of

import {Observable} from 'rxjs';

or use

import {MatDialog} from '@angular/material/dialog';

instead of

import {MatDialog} from '@angular/material';

Also, install only part of the library if that allows instead full library.

For example: Since in that project present map and geometry – I use turf library. But I don’t use all library options. So I removed @turf/turf from package.json and install only those functions, that I need: @turf/center, @turf/bbox etc.

Third step:

Use serverside compression.
This step added the most significant result for minimizing of network usage.

I have Nginx on the server-side (with the reverse-proxy)

On the entry-proxy configuration, I have nothing instead of simple proxying:

location / {
    proxy_pass ;
    proxy_set_header Host            $host;
    proxy_set_header X-Forwarded-For $remote_addr;
}

On the destination-proxy configuration, I’ve set up gzip:

server {
...
    gzip on;
    gzip_http_version 1.0;
    gzip_comp_level 5;
    gzip_types    text/plain application/javascript application/x-javascript text/javascript text/xml text/css;
    gzip_proxied any;
    gzip_min_length 256;
    gzip_vary on;
...
}

Note:

  • gzip on – switch on compression;
  • gzip_http_version – when use proxy content doesn’t compressed, so after googling I’ve found this solution;
  • gzip_comp_level – vary from 1 to 9;
  • gzip_proxied any – all proxied requests needs to be compressed;
  • gzip_min_length – compress content if size bigger than this value;
  • gzip_vary – use cache;
  • gzip_types – define mime types for compression – my goal – minimize js and css mostly;

Webpack bundle analyzer

In the way to use webpack-bundle-analyzer I’ve added build task to my package.json file (Angular5 at the moment):

"stat-build":"ng build --prod --stats-json --aot --named-chunks --environment=prod --build-optimizer"

and use it:

npm run stat-build

And once more thing. Check all unused imports. Sometimes it helps to avoid errors.

This is all for now.
Happy coding

Leave a Reply

Your email address will not be published. Required fields are marked *