django-vite
django-vite copied to clipboard
Load Assets' Images
Thanks for this really helpful library.
Is there a possibility to load the static images that are inside the static folder ? Like Django's {% static %}.
For example:
When I visit an image using {% static %} it shows 404 error.
But when I change the port to 3000 it shows that django-vite imported it.
Thanks !
It's possible, you need to import them into you main.js file like CSS. But be aware that, last time I tested this, Vite put URLs of those static files a bit messy in the manifest.json to be load with Python safely.
For now, static files (like images, fonts ...) are not supported by django-vite. You should use the {% static %} of Django.
I keep your issue open, and if other peoples are demanding of this feature I will give it a look, or if you want to do a PR and implement it, you're welcome.
It would be great if the django-vite supported images. Or any expample how handle images in development and build state
I got stuck with this for a little while. Just a note for anyone looking to import images and use them elsewhere within their javascript frontend:
As per Vite docs https://vitejs.dev/guide/assets.html you can just:
import imgUrl from './img.png'
document.getElementById('hero-img').src = imgUrl
They won't work with django-vite in dev mode right away, because it'll be hitting the django dev server using a relative path, rather than your vite dev server.
To fix, just add the following option to your vite config:
server: {
origin: "http://localhost:5173",
}
That way, you'll get absolute generated asset URLs during development docs ref: https://vitejs.dev/config/server-options.html#server-origin
Another way of achieving this is to use a copy plugin (such as https://www.npmjs.com/package/rollup-plugin-copy) to copy any assets you need in Django during your Vite build process - then when Django grabs your dist output folder you can just use static to reference your assets.
This is useful if the assets themselves aren't bundled by Vite.
@aresti this should be documented :) faced the same issue