Bundle analyzer for Angular app

Sooner or later, when your application grows and becomes quite large, there is a need to optimize your code.
One such tool is the webpack bundle analyzer. As stated in the documentation:
Visualize size of webpack output files with an interactive zoomable treemap.
This module will help you:
1. Realize what’s really inside your bundle
2. Find out what modules make up the most of its size
3. Find modules that got there by mistake
4. Optimize it!
First of all, we need to install webpack bundle analyzer.npm install --save-dev webpack-bundle-analyzerThen we create file dist/stats.json with command:ng build --stats-jsonRun analyzer:npx webpack-bundle-analyzer dist/stats.json
Webpack bundle analyzer is started at http://127.0.0.1:8888
You can open your browser and see what size is used every module:

The bundle size is 198.44 KB now.
Now we import “moment”module and look it again.
import { Component } from '@angular/core';
import * as moment from 'moment';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.sass']
})
export class AppComponent {
ngOnInit(){
let date = moment().date();
}
}

The bundle size is grown up to 572.95 KB. It is too much for app like this and you have to replace this module with another. Anyway if you want to use moment in your project you can decrease size using custom-webpack.
First of all, install it.
npm install --save-dev @angular-builders/custom-webpack
Create in you root path webpack.config.js. I’ll ignore moment locale.
"use strict";
const webpack = require("webpack");
module.exports = {
module: {
rules: [],
},
plugins: [
new webpack.IgnorePlugin({
resourceRegExp: /^\.\/locale$/,
contextRegExp: /moment$/,
})
],
};
Change build options in your angular.json:
"architect": {
"build": {
"builder": "@angular-builders/custom-webpack:browser",
"options": {
"customWebpackConfig": {
"path": "./webpack.config.js",
"replaceDuplicatePlugins": true
},
}
}
}Then you need to build (ng build --stats-json)your app and run analyzer again.

You can see that moment locale is disappeared and our bundle size is decreased, but my app is still good working.
It can be different modules in your case, but you always can manipulate it.