uglow
uglow

Reputation: 221

Applying gzip compression to files served by grunt-contrib-connect

It's pretty simple: I want to simulate the page-size of my website using grunt-contrib-connect before I deploy the site onto Apache.

With Apache, it's pretty straight-forward to turn on gzip-compression. However, with grunt-contrib-connect, I haven't found a way to make it work. Here's what I've tried so far in my Gruntfile.js:

var compression = require('compression');

...
// The actual grunt server settings
connect: {
  dev: {
    options: {
      open: false,
      base: 'dev',
      port: '4000',
      hostname: 'localhost',
      livereload: 35729,
      onCreateServer: [compression()]
    }
  }
}

I've also tried:

connect: {
  dev: {
    options: {
      open: false,
      base: 'dev',
      port: '4000',
      hostname: 'localhost',
      livereload: 35729,
      middleware: [compression()]
    }
  }
}

I can serve the files up correctly, but when I use Chrome Dev tools to look at the Network requests, I can see that no compression is being applied to any files served by the connect webserver. What am I doing wrong?

Upvotes: 5

Views: 1414

Answers (2)

nwalton
nwalton

Reputation: 2061

Not sure if this will help anyone, but I had trouble figuring out what to do where the above just uses compression(). I assume that's shorthand for a function that will compress files on the fly. Since I didn't find any info that looked like it would tell me how to do that, I just used grunt-contrib-compress to gzip all of my files into a new directory.

Gruntfile entry:

compress: {
  dist: {
    options: {
      mode: 'gzip'
    },
    expand: true,
    cwd: 'dist/',
    src: ['**/*'],
    dest: 'dist_compress/'
  }
}

Then I added a new server entry for connect, with a small middleware function to change the Content-Encoding header. That allowed me to do local performance tests with gzip enabled.

Gruntfile entry:

connect: {

  server_gzip: {
    options: {
      port: 9004,
      livereload: false,
      base: 'dist_compress',
      middleware: function(connect, options, middlewares) {
        middlewares.unshift(function(req, res, next) { 
          res.setHeader('Content-Encoding', 'gzip');
          return next(); 
          });

        return middlewares;
      },
    }
  }
}

Note that livereload needs to be turned off since that will cause things to fail.

Upvotes: 0

Vishwanath
Vishwanath

Reputation: 6004

In the grunt-contrib-connect task, if you supply an Array to middleware, it will completely replace the default middleware with what you provide. But if you specify the middleware option as a function, it works as you would expect (chaining your middleware to the default middleware

middleware: function(connect, options, middlewares) { 
    middlewares.unshift(compression()); 
    return middlewares; 
}

Upvotes: 4

Related Questions