Intro

The with having assets in a designated folder that isn’t the public folder the browser can open and check is that sometimes bundlers can’t fetch the resources.

I ran into this using React - JS Library and vite but not with Astro.

Solution

The fix is to either import them using a JS import if they’re static (for example if the the path’s static) but if the path to the asset is only availble during runtime like in the following example, then we need the to use new URL('...', import.meta.url).
Example:

// This function tells Vite to retrieve the URL for the image, needed for the bundler!
const getImageUrl = (relativePath: string) =>
    new URL(`../assets/images/${relativePath}`, import.meta.url).href; 
 

This informs Vite to load these assets in the dependency graph and optimizes them.


References