DEV Community

Rex
Rex

Posted on

Enable gzip compression on build for a Nrwl/nx React project and configure Nginx server to serve compressed files

The bundle size is critical to a web application. Bigger bundle sizes increase the initial response time. Nrwl/nx’s build configuration offers many solutions to reduce bundle sizes, such as tree shaking/optimisation and minification, but gzip compression is not one of them by the time of this article.

Compressing and serving compressed files from our webserver can further reduce our web application’s bundle size by as much as 70% and more. It is easy to configure the Nginx server to compress files on the fly using gzip directive. However, compressing on the fly for every request costs server CPU resources, and it is a waste because we can and we should compress our files beforehand.

We can produce compressed gzip files on build for a Nrwl/Nx project, by extending Nrwl/nx’s webpack configurations and add compression-webpack-plugin.

For a React Nrwl/nx project, steps to extending Nrwl/nx’s webpack configurations are:

  1. add a file webpack.config.js with the below content under your app’s folder or somewhere else. The content is copied from the default configuration from Nrwl/nx and added the compression-webpack-plugin plugin.

  2. Add compression-webpack-plugin to your dev dependencies in your package.json file. Note, for webpack 4.x (which is the version for nrwl/nx 12.x), the highest version of compression-webpack-plugin you can use is 6.1.1. Make sure you install it with your favourite package manager.

  3. In your workspace.json file, replace webpackConfig under [your-app-name]/targets/build node to point to above file webpack.config.js.

After the above steps, rebuild your app. You should see extra .gz files are generated along with your original bundle files. Please note, if you encounter the “heap out of memory” error during the building process, try to increase the node’s memory usage globally like this “export NODE_OPTIONS= — max_old_space_size=4096” and retry.

To enable serving gzip files for a Nginx web server, just add gzip_static on in your app’s nginx configuration file. For an Ubuntu server, the file would be /etc/nginx/sites-enabled/[your-app-conf-file]. Then restart or reload nginx with a command like this: sudo service nginx restart

To check, open your browser’s developer tools, open the network tab, make sure disable cache is enabled and refresh your app. Then inspect one of your bundle files. You should see that the downloading sizes of your bundle files are much smaller. Click one of your bundle files, and in the Headers tab, you should see Content-Encoding: gzip under Response Headers section.

Top comments (0)