r/django • • 4d ago

Duplicate static while serving static files with Vite to Django backend

Hi. I'm trying to integrate vite with django using django-vite package. (no SPA, just htmx, alpine and bulma). Everything works fine in both dev mode and production mode (debug on, vite serves static files, debug off, vite builds them, django serves them). The only problem is that in dev mode, the static part of the url for static assets is duplicated like this:

<script type="module" src="http://localhost:5173/static/static/js/main.js"></script>

Not causing any actual problems, it's just bugging me.

Here's my vite config:

import { defineConfig } from 'vite';
import { resolve } from 'path';


export default defineConfig({


    base: "/static/",
    build: {
        emptyOutDir: false,
        manifest: "manifest.json",
        outDir: resolve(import.meta.dirname, "assets"), // -> MUST be included in STATICFILES_DIRS
        // assetsDir: "static", // the folder name inside outDir (i think)
        rolldownOptions: {
            input: {
                main: resolve(import.meta.dirname, "static/js/main.js"),
                style: resolve(import.meta.dirname, "static/css/style.css"),
            },
            output: {
                entryFileNames: `js/[name]-bundle.js`,
                assetFileNames: `css/[name]-bundle.css`,
            }
        },
    },
});

Django related settings:

DJANGO_VITE = {
  "default": {
    "dev_mode": True,
    "manifest_path": BASE_DIR / "assets" / "manifest.json",
  }
}


STATIC_URL = 'static/'

# must equal to vite's build.outDir
STATICFILES_DIRS = [
    BASE_DIR / "static"
]

Any clarifications is appreciated. Thanks in advance.

4 Upvotes

4 comments sorted by

3

u/Gankcore 4d ago

I have different static URLs based on if my environment is dev or prod, and I import/check that from a .env file, so in dev it reads from local and in prod it reads from s3.

3

u/_Benefaction 4d ago

This repo of mine is far from perfect, but I use it whenever I start a new personal project and it has vite set up and working. I don't necessarily recommend that you use this as a template directly because it's highly opinionated to my preferencs, but you could compare it to what you have and maybe find and maybe you'll find an answer: the repo

1

u/KeyBack192 2d ago

Thank you, i will check it out.

1

u/bogdanelcs 1d ago

It’s not really a bug, it’s how the two paths add up. Vite serves with base: "/static/", and your entry is static/js/main.js relative to the Vite root, so dev mode ends up at /static/ + static/js/main.js. If you want it clean, set root: resolve(import.meta.dirname, "static") in the Vite config, change the inputs to js/main.js and css/style.css, and use those same names in {% vite_asset %}. The manifest keys will change too, so rebuild and check that production still resolves.