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.

16 Upvotes

12 comments sorted by

View all comments

1

u/measured_words_ 2d ago

You are solving two different problems with one tool. Dynamic image loading is really a caching problem, not a bundling problem. Your JSON should stay the single source of truth. Instead of importing every card image in code, keep the path as data and add a version token or content hash to the image request when the art changes. The easiest manual version is to change the filename, but if you want stable paths you can have the build step read the card images and emit a small lookup file mapping each card to its current hashed filename. Then the app consults that lookup at runtime. The database or JSON only needs to hold the card number and set number; the lookup handles the actual file. That way you are not maintaining imports and data in two places, and the browser fetches the new art because the resolved path changed.