How to make Laravel Vite copy static assets versioned to build folder
Asked Answered
S

1

2

I'm experimenting with Laravel Vite but can't seem to figure out how to have the build command move static assets. Instead, it embeds the images "in" the css file trough base64.

So far I've figured out that you need to reference your images relative to the source .css / .scss file.

Like so in /resources/app.css;

.arrow {
  background-image: url('../img/icons/arrow.png');
}

When I run npm run build the end result is a css file containing the image as a base64;

.arrow {
  background-image: url(data:image/png;base64,xxxxxxxxxxxxxxxxxxxx);
}

My desired end result, however, would be that Vite would copy and version that exact image into /public/build/assets/img/icons/arrow.xxxxxxxxxx.png and the processed css would be;

.arrow {
  background-image: url('/build/assets/img/icons/arrow.xxxxxxxxxx.png);
}
Sixtyfour answered 19/8, 2022 at 11:26 Comment(0)
S
3

Figured it out. Turns out it's actually a feature where Vite inlines images < 4kb by default. The setting can be overwritten by defining build.assetsInlineLimit

export default defineConfig({
    build: {
        assetsInlineLimit: 0,
    },
    plugins: [
        laravel([
            'resources/css/app.scss',
        ]),
    ],
});

As stated in the docs;

Assets smaller in bytes than the assetsInlineLimit option will be inlined as base64 data URLs.

https://vitejs.dev/guide/assets.html

https://vitejs.dev/config/build-options.html#build-assetsinlinelimit

Sixtyfour answered 21/8, 2022 at 8:31 Comment(1)
Thank you for this. I was using Vite::asset() in blade templates and the images where not being added to the build directory. All it did was throw an error saying the file could not be found in the manifest. This solution fixed it.Frenetic

© 2022 - 2024 — McMap. All rights reserved.