Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use local static images in Svelte

Tags:

svelte

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.

like image 215
JiaJing Loh Avatar asked Jul 05 '19 02:07

JiaJing Loh


People also ask

Where does svelte project store images?

Any static files used in documents such as images, icons or files for download are stored in src/static directory.


Video Answer


4 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" />
like image 180
Hadi Avatar answered Oct 18 '22 20:10

Hadi


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;
}
like image 28
Luis Avatar answered Oct 18 '22 19:10

Luis


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'

like image 6
Andrew1325 Avatar answered Oct 18 '22 21:10

Andrew1325


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>
like image 2
Rajodiya Jeel Avatar answered Oct 18 '22 20:10

Rajodiya Jeel