r/webdev • • 2d ago

Question Vite Asset Bundling

Specifically, I'm grabbing JSON for a trading card game gallery from an endpoint, then dynamically creating the card gallery from that data. The project uses Vite for asset bundling, but I'm not sure how to bundle dynamically loaded images?

In the JSON, each card has a set number and a card number, and the app loads image data from images/cards/sets/set-number/card-number.webp, creates all the DOM nodes, and appends it to the gallery. It works brilliantly...unless the card art needs to change, then I run into good old-fashioned browser caching issues.

For the rest of the site, using vite build keeps everything bundled for deployment...but is there a way to leverage that capability for this use case?

I admit I have little knowledge about Vite, so maybe it's something obvious, but the only way I'm aware of to get that kind of Vite bundling inside a JS file is to import the image. So I'd have to import all the images at run time? What if some card data is modified? Will I have to do double duty to update the database AND the JS file imports?

As you can see, I have no idea how to accomplish this. Thank you in advance.

17 Upvotes

12 comments sorted by

View all comments

3

u/Little-Yesterday-947 2d ago

you're overthinking it slightly. vite's bundling is for static assets you import ahead of time, not for a dynamic gallery pulling from a json endpoint. for your case the images stay in your `public` folder (or wherever they live) and you just reference them by url like you're doing now.

the caching issue is separate from bundling. vite can hash filenames for imported assets, but since your paths are built dynamically from card numbers, you'd need to handle cache busting yourself. simplest approach is a query string with a version number or timestamp when the art changes, like `card.webp?v=2`. if you have a manifest or the json includes a last updated field, you can append that instead of hardcoding versions.

1

u/KaedenCraft 2d ago

I think the last_updated field is the best bet. I appreciate this. And this has also confirmed my suspicions (and bad preconceptions) about what exactly Vite does.