Let’s Make Our Bundle Size Even Smaller

In this example, I used React, but making the bundle size smaller is basically the same thing on all frameworks. so I used create-react-app which is a simple tool for starting with react framework without the need to configure webpack yourself. This is the result I’ve got after running npm run build on my project

First minified JS file 2.7MB

The file size looks quite large, so let’s analyze it and see what’s taking so much space. source-map-explorer is an npm package that analyses bundled JS file and tells you what the file is made of (dependencies and sizes).

npm install -g source-map-explorer
source-map-explorer bundle.min.js bundle.min.js.map

And here is the result:

As I mentioned before, the node modules are taking most of the file’s size, and the first two things that got my attention from the analyses is that react-icons and emoji-mart are pretty heavy (probably it’s because they used a lot of media assets).

from a quick search in the code I’ve found this line:

import { FaUpload } from 'react-icons’;

React-icons is a simple UI module for importing generic icons to the app.

This kind of import in this specific case will import all the icons to our app which doesn’t make sense because I only wanted to use one icon, from a quick lookup in the documentation I ended up with this kind of import.

import FaUpload from 'react-icons/lib/fa/upload'

Since react-icons is divided into subfolders it allows us to import only the required piece of code. There are other examples of packages that use the same method such as “lodash” which is one of the most popular javascript libraries for utility functions.

That did the trick, our bundle size got smaller with no effort at all.

Our second problem was the emoji-mart dependency. I won’t go into too many details because that example is too specific but I managed to reduce the emoji-mart package by just replacing it with something smaller that answered my application’s needs. If you have a large package out there, there must be a discussion about it in the repository so It’s worth to take a look and even contribute a solution for it.

Now let’s talk about gzip. gzip is a file format used for compressing data. It’s been supported on almost any browser which results in easy implementation on the client side using “Content-Encoding” header.

This way the client gets the compressed data and decompress it on run-time. I’ve used gzip-all package for generating the compressed versions of the minified javascript & CSS files.

We managed to get our file size really small, we can now change the file type back to .js and send it to the world and reduce the time it takes for the app to be loaded.

read original article here