I was following the tutorial () 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.

1

5 Answers

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" /> 

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> 
1

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; } 
4

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'

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> </div> 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.