How to set "Content Encoding" to enable gzip files for Webpack server
Asked Answered
A

2

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

Aday answered 21/7, 2016 at 10:23 Comment(2)
Do you use webpack to serve files on production environment ?Echino
This might help: #23600729Abscess
D
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();
});
Disband answered 1/8, 2017 at 14:45 Comment(0)
K
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
    }),
]
Kitten answered 8/9, 2020 at 12:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.