i am totaly newbi in sveltekit,
my main question is : Where to put images with SvelteKit? and how use it. in static folder, right?
But this causes a problem: when in this route : "@domain/dashboard" ,I use this code:
<img src="user.png" />
it try to find it in @domain/user.png and everything is ok! but when i use this route: @domain/users/1 it try to find it in @domain/users/user.png exept @domain/user.png.
please help me.
ps: i see there is topics that recommend use something like this:
import logo from '$lib/assets/user.png';
so if i copy images into lib folder, What is the reason for static folder?
To make links to static
work anywhere, you just have to make the path absolute, by starting with a /
(and possibly the base
, if the application is to be hosted on a sub-path of the server).
static
should generally only be used for resources that have to be at a fixed path on the server, e.g. /robots.txt
. Since the name cannot change but the file contents might, these files are served in a way that prevents caching which is wasteful for larger resources.
<img src="/user.png" />
<!--
For example for static sites for GitHub pages which are on:
https://[user-name].github.io/[repository-name]/
base should be set to '/[repository-name]'
-->
<img src="{base}/user.png" />
Things in static
are available to be referenced as is.
Everything in lib
is intended for import, which allows for the possibility of transforming the asset first. E.g. style sheets in a language that has to be preprocessed such as SCSS.
Importing the asset also ensures that a hash is added which allows for the files to be cached indefinitely. If the contents change, the file will have a different path resulting in a cache miss.
<script>
import userSrc from '$lib/images/user.png';
</script>
<img src={userSrc} />
It is also possible to do relative imports e.g. import img from './image.png
, which is something to consider if an asset is only used in one route and you want to keep the relevant files closer together.