My Profile Photo

Simon Chiu


A software developer's thoughts, stories and ideas.


Simple steps to drastically reduce your webpack bundle size

Have you ever got so bogged down churning out features for your product and completely forgotten about performance? This happened to me recently and I’m embarassed to say the bundle.js reached an epic 3.2mb. It only occurred to me when I was navigating to my site on a 3G connection that it was so excruciatingly slow.

The first change I made was to add the following plugins to the webpack.config.js

new webpack.DefinePlugin({
    'process.env': {
        NODE_ENV: JSON.stringify('production')
    }
}),
new webpack.optimize.AggressiveMergingPlugin(),
new webpack.optimize.UglifyJsPlugin()

This reduced my bundle from 3.2mb to 1.2mb.

Finally, I enabled gzip in nginx on my production server. Run the following command on your server: nano /etc/nginx/nginx.conf

Scroll down to the Gzip settings and uncomment the following lines.

gzip on;
gzip_disable "msie6";

gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_buffers 16 8k;
gzip_http_version 1.1;
gzip_min_length 256;
gzip_types text/plain text/css application/json text/xml application/xml application/xml+rss application/javascript application/x-javascript text/javascript application/vnd.ms-fontobject application/x-font-ttf font/opentype image/svg+xml image/x-icon;

Save the file and reload nginx. To confirm Gzip is working correctly run the following command:

curl -H "Accept-Encoding: gzip" -I http://www.YOURWEBSITE.com/bundle.js

The response should contain: Content-Encoding: gzip

The compression reduced my bundle to 330KB, nearly 10% of it’s original size.

comments powered by Disqus