38

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
  • 481
  • 1
  • 4
  • 4

5 Answers5

42

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
  • 439
  • 1
  • 4
  • 4
19

For sveltekit

Assume I have a file src/lib/assets/icon.png

In order to import it:

<script>
   import Icon from "$lib/assets/icon.png"
</script>

<main>
this is a download icon.
<img src={Icon} alt="download icon"/>

</main>
Rajodiya Jeel
  • 319
  • 4
  • 11
  • If the project is using vitePreprocess then it can also parse CSS url("$lib/assets/icon.png") see sveltekit documentation on [Assets Handling](https://kit.svelte.dev/docs/assets) – Athanassios Apr 02 '23 at 21:04
9

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
  • 4,170
  • 12
  • 37
  • 53
Luis
  • 91
  • 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
  • Thanks for that idea - works perfectly! (I put it in the global.css) – Timo Jun 29 '22 at 22:13
  • This assumes images are at /images. A static svelte app should run anywhere, for instance at /theirserver/theirapps/myapp and then the images should come from /theirserver/theirapps/myapp/images. Why should the programmer decide the images should reside at theirserver/images in production? – anneb Apr 18 '23 at 14:19
8

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,519
  • 1
  • 14
  • 25
5

If you are using vitejs/Sveltekit, there is a easy solution mentioned in Vitejs official web site (Click Here).
First inside the script tag :

<script>
const imgUrl = new URL('./img.png', import.meta.url).href
</script>

then inside your Image tag just use that variable,

<img src="{imgUrl}" alt="" />

or,

<div class=" h-screen w-full" style="background-image: url('{bgUrl}') ;">
</div>