Reputation: 115
I'm storing image urls in my store like this
export const artPosts = readable([
{
"title": "Peak",
"tools": ["Blender", "Photoshop"],
"source":"$lib/img/1.png",
"alt": "A surreal neon 80's landscape"
},
Then I'm trying to populate my Art component with the variables:
<script>
import { artPosts } from "../stores.js";
</script>
{#each $artPosts as item}
<div class="wrapper">
<img src={item.source} alt={item.alt} />
<h2>{item.title}</h2>
</div>
{/each}
The Alt text appears but not the image. What is the proper way of doing this?
Upvotes: 2
Views: 533
Reputation: 184336
The problem is probably the $lib
in the path. You will either have to replace that with the final server path or configure your build tool to replace it for you.
Since this is not used directly in an import
, the path will not resolve automatically.
On the assumption that you are using Vite: There is a define
option for that.
E.g.
// vite.config.js
const config = {
define: {
IMAGE_DIR: '/public/images',
},
};
export default config;
<script>
const images = [
"IMAGE_DIR/img1.jpg",
"IMAGE_DIR/img2.jpg",
"IMAGE_DIR/img3.jpg",
]
</script>
{JSON.stringify(images)}
(You probably will want to make the directory identifier fairly distinct, since it will simply replace every occurrence without regarding semantics.)
There also is the option to actually import the images individually:
import img1 from '$lib/img1.jpg';
import img2 from '$lib/img2.jpg';
import img3 from '$lib/img3.jpg';
const images = [
img1,
img2,
img3,
]
That way the $lib
alias will be resolved and the resulting variables will refer to the image path. Of course that is only valid in an actual script, not e.g. JSON.
Upvotes: 1