Thought leadership from the most innovative tech companies, all in one place.

Reduce your React Applications Bundle Size by 75% with Compression

Every React developer should add compression to their bundling process.

One of the most impactful techniques to reduce the bundle size of a React application is compression.

compression is a process in which the size of a file is reduced by re-encoding the file data to use fewer bits of storage than the original file.

Compression is usually achieved with a JavaScript bundler like Rollup or Webpack. For this article, I’ll be showing how to implement compression with Webpack.

This article assumes basic knowledge of Webpack and how it’s configured.

To start, let's see my applications bundle size without compression:

image

My application uses code-splitting so I have more files than an out-of-the-box configuration.

Adding Compression

The first thing to do is install the Webpack Compression Plugin

yarn add compression-webpack-plugin -D

or

npm install compression-webpack-plugin --save-dev

With that installed, import the plugin into webpack.config.js

const CompressionPlugin = require("compression-webpack-plugin")

Next, add the plugin to your plugins array

plugins: [

  ...other plugins,

*  new* CompressionPlugin({

    test: /\.js(\?.*)?$/i,

    filename: "[path][query]",

    algorithm: "gzip",

    deleteOriginalAssets: false,

  }),

],

For the items included:

**test: **Include all assets that pass test assertion.

filename: The target asset filename.

algorithm: The compression algorithm/function.

deleteOriginalAssets: Whether to delete the original assets or not.

I would recommend looking at the Webpack docs for all available options.

Full Webpack Config:

Once you have the config in place, all you have to do is run your build like normal. The files in your build folder will be dramatically smaller.

In my case, every JavaScript file included is 75 percent smaller than the original.

image

Final Note

In order for browsers to read compressed files, they must include the header:

Content-Encoding: gzip

Without this header, your browser will try to read these as normal JavaScript files and crash.

I add these headers to each file when they are uploaded to my CDN on s3.

aws s3 sync --delete ./dist s3://${S3_BUCKET}${BRANCH_NAME} --content-encoding gzip

Your situation might be different but it’s an important thing to point out.




Continue Learning