MrBin99 / django-vite-example

An example Django project with Django Vite
Apache License 2.0
57 stars 21 forks source link

Unable to import assets in JS #5

Open tobyl opened 2 years ago

tobyl commented 2 years ago

Many thanks for this module - it's made working with Vite in Django much easier for me!

I've converted your example app to a React Vite app, and I'm trying to import and use an image from an assets folder inside src:

import reactLogo from './assets/react.svg'

Vite does not complain about the path being wrong (I've tried a few variations) but in the browser the image 404s because the path resolves to:

http://localhost:8000/static/assets/react.svg

I believe the problem is that in dev the url should be the port 3000 url, but I'm not sure the best way to address this. Any guidance would be greatly appreciated!

GatoVuelta commented 2 years ago

Try changing your setting on settings.py -> DJANGO_VITE_DEV_SERVER_PORT

ipeterov commented 1 year ago

I'm having the same issue when importing fonts. The problem is that the urls that Vite generates don't have a host, and the browser tries to get them from the Django server instead of the Vite dev server.

I can't launch the dev server on the same port, and I don't really know what to do.

GatoVuelta commented 1 year ago

I'm having the same issue when importing fonts. The problem is that the urls that Vite generates don't have a host, and the browser tries to get them from the Django server instead of the Vite dev server. I can't launch the dev server on the same port, and I don't really know what to do.

I have made a custom Vite config js file for this and some other cases, it also includes code for building and saving dist files accordingly:

https://gist.github.com/GatoVuelta/a87d0007415d3f34d497269ce6dde09b

Then, if you use SASS you can import fonts and Vite will automatically look for it both on dev and build. For a dir structure like: (root)/static/public/fonts/Poppins-Regular.ttf you could import it like this:

@font-face {
    font-family: 'Poppins';
    font-style: normal;
    src: url('/static/fonts/Poppins-Regular.ttf') format('truetype');
}

In the future, I'll make a starter repo that would include all files and configs for an ideal Django + Vite setup. Note that my approach may not be the best.

pySilver commented 1 year ago

The whole problem is that dynamically included files are referenced as /static/path-to/file.woff2 which assumes that page is opened on the same port. I recall this was fixed by using proxy to backend, instead of loading django served pages directly.

pySilver commented 1 year ago

Turns out it is trivial to solve. Simply set server.origin in your vite.config.js

server: {
  origin: 'http://localhost:5173',
},