23

I was following the tutorial (https://svelte.dev/tutorial/dynamic-attributes) to import local image files. But it didn't work. The image was not found in the app.

Where do I need to locate these images in order to make it works as in tutorial?

let src = './images/background.jpg'
.
.
.
<img {src} alt="background image" />

The browser showed Image not found.

JiaJing Loh
  • 331
  • 1
  • 2
  • 4

3 Answers3

33

Put your images folder in public folder then reference like this:

<img src="images/background.jpg" alt="background image" />

Or

let src = "images/background.jpg";
.
.
.

<img {src} alt="background image" />
Hadi
  • 349
  • 1
  • 3
  • 4
6

Here is another way to use images in svelte:

.banner-container {
    background-image: url("/images/hero-banner.png");
    background-repeat: no-repeat;
    background-size: 100% auto;
}
colidyre
  • 3,401
  • 11
  • 33
  • 47
Luis
  • 61
  • 1
  • 3
  • 1
    Is this the preferred way to use images in Svelte? This is the only way I'm able to link to images. Doing it from JS, like the top rated answer, doesn't work for me. – HaulinOats Sep 21 '21 at 16:05
  • Worked for me, thanks! – BMB Nov 02 '21 at 18:30
5

The local images you will use need to be referenced as relative to the index.html file in the public folder. So in your case:

let src = './images/background.jpg'

background.jpg would need to be in a folder called "images" inside the "public" folder.

You could just reference it as let src = 'images/background.jpg'

Andrew1325
  • 3,283
  • 1
  • 11
  • 24