In the CSS section of a Svelte file, suppose I use a background-image:
div { background-image: url(img/bg.jpg); }
The image file is in the static
folder (static/img/bg.jpg). This simple example runs perfectly in dev mode.
If I try to build the project (with adapter-auto), I get a warning:
img/bg.jpg referenced in (...) didn't resolve at build time...
and if I run the app it fails to find the image (at /_app/immutable/assets/img/bg.jpg
).
This answer: https://stackoverflow.com/a/75716822/494979 suggests to define an alias in the vite.config.ts
file:
export default defineConfig({
resolve: {
alias: {
$img: "/static/img",
},
},
});
and change the CSS to:
div { background-image: url($img/bg.jpg); }`
The built project now correctly loads the image (from /_app/immutable/assets
).
But now it doesn't work in dev mode (tries to load the image from /static/img/bg.jpg
instead of /img/bg.jpg
).
The problem would be the same for other assets loaded from the CSS, like fonts (with @import
).
The SvelteKit docs (https://kit.svelte.dev/docs/assets) say: "For assets included via the CSS url() function, you may find vitePreprocess useful.", but I have no idea how.
How can I have a configuration that works for both dev and build, as can be expected?
I came across your question as I had the pretty much same issue. For me, I followed guide from Vite docs which states:
Note that you should always reference public assets using root absolute path - for example, public/icon.png should be referenced in source code as /icon.png.
Following it, it worked in both dev and production. So that I'm referencing images as /img/bg.jpg
.