I'm using an array of dummy data to test how I could display information from an api. In that data, I have a relative image path, for some images I've stored locally in $lib
for simplicity in testing.
I loop through each object in this dataset, and create a component with the relative image path passed to the object. In my testing the relative paths are resolving correctly, but I'm unable to load the images dynamically.
After doing a bit of digging, it seems that this is because of the file structure and permissions with $lib
. It seems that image import is easy to do if I use a static solution with the images, and just dynamically adjust the relative url, but I want to be able to use Vite's performance improvements when it comes to images. Indeed, Sveltekit documentation recommends storing images in a directory within $lib
for this exact reason.
In the component I can manually import each image from $lib
and it works as expected like so:
<script>import img from '$lib/assets/sample-image.jpg'; </script><img src={img} />
But for the life of me I can't figure out how I can change the import path using a dynamic prop. I imagine it would look something like this:
import img from '$lib/assets/{object.imageUrlProp}';
Or some type of direct access in the image src
similar to how static usage would look like:
<img src="$lib/assets/{object.imageUrlProp}" alt="Image" />
But neither of these are valid syntax.
How can I dynamically import images stored in $lib
within a component in Svelte?