Laravel mix: config to convert images to base 64

Viewed 505

I'm looking for some pointers on how to set up Laravel mix to find image assets under a certain threshold size and recode them in the stylesheet as Base 64 strings. I can achieve this with Webpack using url-loader, but I'm struggling to get the config working in my Mix config. What I've tried:

const mix = require('laravel-mix');

mix.setPublicPath('public_html/');
mix.js('resources/uxmaps/js/app.js', 'uxmaps/js/app.js').version()
.webpackConfig({
        module: {
            rules: [
{
                test: /\.(png|jpg|gif)$/i,
                use: [
                  {
                    loader: 'url-loader',
                    options: {
                      limit: 8192,
                        outputPath: 'images'
                    },
                  },
                ],
}
            ]
        }
    })
   .sass('resources/sass/app.scss', 'css/main.css')

This compiles without errors, and yet it simply doesn't work; my background image in my sass file for example background-image: url(/assets/logo.jpg); (3kb) remains as-is in the ouputted css.

Secondly, I have also tried separating out the url-loader part of the config into a separate file (imported module) as per the mix docs: https://laravel-mix.com/docs/5.0/extending-mix (see 'Usage' section at the bottom). Same result: it compiles without errors, but simply doesn't work.

Finally, I have also tried doing this with this Post CSS plugin but on compilation it was giving me errors relating to dependency versions (I think this is outdated now).

Any pointers as to why this code isn't working properly, or otherwise any other ways to convert images to inline Base 64 with Laravel mix ?

Thanks

EDIT I discovered that I was using absolute paths for the image, and therefore Mix was ignoring them, as per the docs. If I change to a relative path, then Mix outputs the css as background-image: url(/images/logo.jpg?dab783c3f2e3b389830733b050848c8a); and- get this- url-loader takes the jpg file, and gives me a file called 'logo.jpg' in a public_html/images folder, which isn't a jpg at all, but a text file containing Base64 code.... :/

How do I get that Base 64 code to be written into the stylesheet?!

1 Answers
mix.override(function (webpackConfig) {}) 

... will be triggered once the webpack config object has been fully generated by Mix.

Maybe here try to remove their file-loader and add yours setup.

Related