1 June 2017

Tutorial for serving static gzip with webpack module bundler and nginx server. When you would use nginx directly to compress the output, it would do it on the run and with some load increase the cpu usage. It's better to compress your huge project a single time and then serve it when possible. So webpack creates the compressed files and nginx servers gzip instead of the original when possible.

Webpack

Install webpack compression plugin and add it to dev dependencies.
Source code viewer
  1. npm install --save-dev compression-webpack-plugin
Programming Language: Bash
Edit your webpack production config file to zip the files on compilation. The config has some basic extensions of javascript, styles and fonts to compress only where it counts. Threshold limits the file size that is valid for compression and minRatio defines the minimum compression ratio which the zip file is accepted, everything above that is not compressed to get the optimal page load speed.
Source code viewer
  1. const CompressionPlugin = require('compression-webpack-plugin');
  2.  
  3. module.exports = {
  4. plugins: [
  5. new CompressionPlugin({
  6. asset: '[path].gz[query]',
  7. algorithm: 'gzip',
  8. test: /\.(js|css|ttf|svg|eot)$/,
  9. threshold: 10240,
  10. minRatio: 0.8,
  11. }),
  12. ]
  13. }
Programming Language: ECMAScript

Nginx

Make sure you have http_gzip_static_module with "nginx -V". If you don't have the module included you might need a custom compiled nginx for an example Ubuntu server nginx packages have it included by default. Add to nginx configuration.
Source code viewer
  1. # Enable ngx_http_gzip_static_module for serving compressed files when possible.
Programming Language: nginx

Chrome

Validate that your styles get compressed by "Content-Encoding: gzip" response header.valid gzip response header