6

I have created an angular-universal app using Webpack server. I have used the "compression-webpack-plugin" to compress my js/html files so that I can serve them from server to the browser. The zipped files are getting created properly through that plugin.

The problem:

While the browser shows that it can accept gzip or deflate files (Accept-Encoding:gzip, deflate, sdch), my webpack server isn't sending the gzip files to the browser.

How can I configure my webpack server in such a way that it will send gzip files to the browser when the browser makes the call?

TIA

Chetan Unkule
  • 101
  • 1
  • 4

2 Answers2

2

Here's my webpack and express server setup:

// webpack.config.js

plugins: [
  ...
  new CompressionPlugin({   <-- Add this
    asset: "[path].gz[query]",
    algorithm: "gzip",
    test: /\.js$|\.css$|\.html$/,
    threshold: 10240,
    minRatio: 0.8
  })
...
]

// server.js

app.get('*.js', function(req, res, next) {
  req.url = req.url + '.gz';
  res.set('Content-Encoding', 'gzip');
  res.set('Content-Type', 'text/javascript');
  next();
});

app.get('*.css', function(req, res, next) {
  req.url = req.url + '.gz';
  res.set('Content-Encoding', 'gzip');
  res.set('Content-Type', 'text/css');
  next();
});
Isaac Pak
  • 4,467
  • 3
  • 42
  • 48
2

Isaac's answer helped however my issue was that I had the below from the boilerplate I used:

// http://expressjs.com/en/starter/static-files.html
app.use(express.static('public'));

When you have that you have to put this 'route' before:

// Must come before the use public folder!!
app.get('*.gz', function(req, res, next) {
  res.set('Content-Encoding', 'gzip');
  res.set('Content-Type', 'text/javascript');
  next();
});

// AFTER Gzip fix
app.use(express.static('public'));

I can't name the file the same as the original also so I changed it to have .gz (webpack complains if you try to name it the same as the bundle it generates + it doesn't seem to even work in latest webpack)

plugins: [
    new CompressionPlugin({
      filename: '[path].gz[query]',
      algorithm: 'gzip',
      test: /\.js$|\.css$|\.html$|\.eot?.+$|\.ttf?.+$|\.woff?.+$|\.svg?.+$/,
      threshold: 10240,
      minRatio: 0.8
    }),
]
OZZIE
  • 6,609
  • 7
  • 55
  • 59