Reduce your React Applications Bundle Size by 75% with Compression

Ashutosh Kaushik
2 min readDec 14, 2022

--

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.

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

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:

{
node: {
fs: "empty",
},
entry: ["./src/index.tsx"],
module: {
rules: [
{
test: /\.(ts|tsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
},
},
{
test: /\.css$/i,
use: ["style-loader", "css-loader"],
},
{
test: /\.svg$/,
use: [
{
loader: "svg-url-loader",
options: {
limit: 10000,
},
},
],
},
],
},
resolve: {
extensions: [".tsx", ".ts", ".js", ".jsx", ".css"],
},
output: {
filename: "[name].[hash].js",
chunkFilename: "[name].[hash].js",
publicPath: "/",
},
mode: "production",
plugins: [
new HtmlWebpackPlugin({
template: "public/index-prod.html",
}),
new CompressionPlugin({
test: /\.js(\?.*)?$/i,
filename: "[path][query]",
algorithm: "gzip",
deleteOriginalAssets: false,
}),
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: JSON.stringify(process.env.NODE_ENV),
},
}),
],
}

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.

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.

We need to add these headers to each file when they are uploaded.

Thanks for Reading, it might be helpful for you.

--

--

No responses yet