django-vite icon indicating copy to clipboard operation
django-vite copied to clipboard

Load Assets' Images

Open ayadcodes opened this issue 3 years ago • 5 comments

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.

ayadcodes avatar Aug 25 '21 14:08 ayadcodes

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.

MrBin99 avatar Aug 26 '21 16:08 MrBin99

It would be great if the django-vite supported images. Or any expample how handle images in development and build state

Sergdan1992 avatar Sep 05 '22 14:09 Sergdan1992

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

aresti avatar Dec 14 '22 21:12 aresti

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.

emab avatar Jun 09 '23 08:06 emab

@aresti this should be documented :) faced the same issue

pySilver avatar Jul 14 '23 17:07 pySilver