Weight Loss with Browserify

TL;DR Browserify bundles too big? Use Disc to find trouble points. Then replace big utility-knife packages with smaller, narrow-focus equivalents from sites like microjs.com

Our cobrowsing web app was taking too many precious seconds (read: an eternity) to pop in the browser. We had focused on adding features without keeping an eye on steadily-increasing load times. The code consisted of 3 Browserified bundles totaling 1.9mb minified-yikes. I brought that size down to 730kb with my two new favorite methods: light discs and lies.

before_and_after
Before and after.

1. Find the pain points

The first step to losing those extra bytes is finding out who is contributing what to your bundle. Disc by @hughskennedy is a tool that analyzes every module inside your bundle and displays a graphical breakdown of bytes per module. You can install Disc with [sudo] npm install -g disc
Let’s say you want to analyze the bundle core.js. Create a Disc diagram with these steps:
browserify --full-paths core.js > core-bundle.js
discify core-bundle.js > core-bundle.html
open core-bundle.html

Radial diagram generated by Disc.
Click for a live demo.

Now you’ve got a radial diagram of all the modules that make up your bundle. Each colored graph segment represents one module. Mouseover any segment to see the module name and size. Disc provides additional convenience options such as automatically highlighting particular module types; see the official Disc page for more.

2. Prune your packages

Now it’s time to act on the information generated by Disc.

  • Remove unused packages. If I was reading this post before trying Disc I’d scoff and say “right, who would forget to remove a reference to an old package?” In one of our files, I discovered a single unused package (aws-sdk) that was eating up over 500kb minified. As code grows, dead references can hide in the weeds.
  • Replace larger packages with smaller equivalents. If you are using only a tiny fraction of that huge utility knife package, consider replacing it with a smaller package or packages that meet your needs. The site microjs.com provides a catalog of small, narrow-focus npm packages. For example, we were using the promise library Bluebird both server and client side. Bluebird is great, but offers far more features than we needed while contributing a sizable chunk to the bundle. I replaced it with a smaller but adequate promise library called lie.
  • Watch for unnecessary browserify shims. Browserify is nice enough to conditionally inject browser shims for node modules like crypto. If you reference crypto in your bundle, in goes the crypto-browserify shim. This is great unless, as was our case, all we needed was an MD5 routine and instead added 100+kb of dead weight to the package.

That’s all I got. Hope this helps your Browserify bundles get ready for summer.

Leave a comment

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