I am new in web development and I find it very useful to implement this in production build for performance improvement. And here, I’ll try to share this and hopefully it will be useful for you too!
Please note that if you use Content Delivery Network (CDN) like Cloudflare or Amazon Cloudfront, this functionality has already provided. So you don’t have to handle it manually.
Sample project I use to demonstrate this purpose was using several technical stack which are :
1. React JS as front end library
2. AWS S3 as web hosting service
3. gzipper, a node package for compressing your static files.
First of all, you’ll need to know on what level your app’s performance are. For this, I use Lighthouse Audits in Chrome’s DevTools. Just open DevTools (right click => inspect), then open Audits tab, and click “Run audits” button. Here is how my sample apps performance looks like:
8/100, 7.24 seconds (lighthouse estimation) might be saved if we serve the statics in compressed
Manually Compress Static Files to GZIP
Okay, so now, the “how” part to do compression manually. First you can install any package to compress the files. I use gzipper. To install it, type this in your project’s root directory in terminal:$ npm install gzipper
or
$ yarn add gzipper
if you use yarn
Next step is to adjust your build command so that anytime you build your static files, gzipper then compress it into gzip format. Since I use react and ubuntu, here is how my build scripts looks like in package.json:
“scripts”: {"build”: “react-scripts build && gzipper --verbose ./build ./dist --output-file-format [filename].[ext]”
}
After that, you should set up the hosting server to make sure that it will return http response which includes “content-encoding: gzip” if you use gzip compression, or br for brotli, and deflate for deflate. You can check if it works correctly by inspecting the deployed app, and check in network tab in DevTools, and choose any static files that the browser requested. If it works correctly, you will see something like this:
When you set the hosting server http response rule correctly it will show the content-encoding rule, that gives info for the browser to process the file as gzip compressed file.
Chrome browser supported compression format. It support gzip, deflate, and brotli compression.
Significant performance increase after serve static files in compressed 8 to 71.
With Content Delivery Network (Cloudflare)
If you use Content Delivery Network like Cloudflare or Amazon Cloudfront, you can use their provided functionality for files compression. For Example on my unit conversion project, I use Cloudflare and in the settings of the project, in speed => optimization, you can find the option of which you can choose to apply brotli compression or not.You can set up compression easily if you use CDN like cloudflare
0 Comments