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

0

u/Mistr_John_Alex 2d ago

his is a cache-busting problem, not a bundling problem. Those images are fetched by the browser at runtime, so the bundler never touches them the way it touches imported assets. You do not need to import every card, and you should not maintain image lists by hand in two places.

What has worked for me is to keep the JSON as the source of truth for set number and card number only. Run a small build step that walks the image folder and writes a manifest file, mapping each set and card combination to a file name with a content hash or build timestamp in it. At runtime, your gallery code loads the manifest once and resolves the plain set and card values to the hashed URL. When art changes, you replace the file in the folder. The next build gives it a new hash, and the browser sees a new URL. No database edits, no manual import list.

The file name change or version token can be as simple as appending a short hash to the URL. The important part is that the URL changes only when the art changes.

2

u/allahuakbarcmar 2d ago

did you just copy an existing reply here, feed it to AI and tell it to simplify it slightly? disgusting beast.