martyf's avatar

Base64 inline images in CSS with Mix

I'm new to Laravel and have been exploring Mix (and how it can best work for me) - so new to webpack too.

In reading about webpack, I read that it can base64-encode small images and have them inline in CSS using "url-loader", such as ("Images in CSS class" in https://medium.com/a-beginners-guide-for-webpack-2/handling-images-e1a2a2c28f8d).

Obviously not wanting to bloat the CSS with large images - but having SVG icons (for example) inline and automated would be pretty cool.

As an example, my CSS:

.my-div {
    background-image: url('./../images/icons/badge-check.svg');
}

And:

mix.webpackConfig({
    module: {
        rules: [
            {
                test: /\.(png|jp(e*)g|svg)$/,
                use: [{
                    loader: 'url-loader',
                    options: {
                        limit: 8000, // Convert images < 8kb to base64 strings
                        name: 'images/[hash]-[name].[ext]'
                    }
                }]
            }
        ],
    }
});

mix.sass('resources/sass/app.scss', 'public/css');

The image in question is 572 bytes. I have tried with a 3kb PNG too, but still no joy.

When running, it is simply copying the images to the public/images folder, and the rendered CSS is correct (as in paths to the images are accurate), but I would expect for these two small images, they'd appear inline base64-encoded in the CSS instead.

Am I missing something? Looking too hard? Not searching for the right thing? Or missing some other really cool idea?

0 likes
7 replies
vladv's avatar

And I think if you use base64 images this can't be cached ...

martyf's avatar

@NAGAVINOD424 - I had tried that but still had no impact. Priority-wise isn't the biggest issue but was more for experimenting. The thought of inline base64 svg (instead of multiple HTTP requests) seemed like a good idea.

martyf's avatar

@VLADV - Yes I read that since my initial post too - and that it creates an overhead on processing too. It's that balance of finding the right setup for each project.

munazzil's avatar

Have you change anything use below command in your cmd.

npm run dev
martyf's avatar

@MUNAZZIL - This doesn't address the issue - everything is still referenced as URL, not inline base64 encoded.

Please or to participate in this conversation.