Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Laravel Mix (Webpack 4) Minify() -> gZip

How to gzip minified css/js when using Laravel Mix (webpack 4)

These are a couple of quick notes on how we're gzipping minified css/js files in Laravel Mix (based on Webpack 4) given I couldn't find any real discussion/solution to it online. It's a bit of a hack - let me know if there's a better way! (It's also based on our setup, so you'll need to modify to meet your own needs).

(This is a work in progress - I may find a better solution in which case i'll update this gist).

The problem

Laravel Mix doesnt support compressing your files, the maintainer supposes it's better to let your webserver do it ( laravel-mix/laravel-mix#619 )

  • which sounds like madness to me - why force the webserver to compress the same static files repeatedly on every page request?!

There's solutions that utilize a webpack plugin ( (note you'll need to change 'asset:' to 'filename:' in the solution), BUT that will only compress the unminified files - it wont touch any file created with .minify().

The solution

My core webpack4 knowlege is a bit lacking, so the following is a bit of a hack, but works. Big caveats:

  • This is Laravel Mix code, not core webpack4 code (laravel mix is a fluent interface sat on top of webpack)
  • You'll need to change the paths to the minified files and where you want the .gz files placing accordingly, and the files need to be explicitly named
  • You'll still need to configure your web server to serve up the gzip'd files if the browser states it supports gzip compression (i'm looking into this next, on Apache its looking like the Multiviews solution).
  • This pre-supposes you have gzip installed and pathed (fine on osx without having to do anything).

So, add the following to the bottom of your webpack.mix.js :

mix.then(function () {
        console.log('gzipping files....');
        const { exec } = require('child_process');
        exec('gzip -9 -c deploy/htdocs/assets/js/app.min.js > deploy/htdocs/assets/js/app.min.js.gz', (err, stdout, stderr) => {
            if (err) {
                console.log('ERROR: failed to gzip app.min.js')
            else {
                console.log('COMPRESSED: deploy/htdocs/assets/js/app.min.js.gz');
        exec('gzip -9 -c deploy/htdocs/assets/css/app.min.css > deploy/htdocs/assets/css/app.min.css.gz', (err, stdout, stderr) => {
            if (err) {
                console.log('ERROR: failed to gzip app.min.css')
            else {
                console.log('COMPRESSED: deploy/htdocs/assets/js/app.min.css.gz');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment