Django Vite
django-vite integrates Vite.js into Django projects, allowing for fast frontend development with Hot Module Replacement (HMR) and efficient production builds. It handles manifest file parsing and asset serving for both development and production environments. The current version is 3.1.0, with frequent patch releases and minor updates.
Warnings
- breaking The configuration format for `DJANGO_VITE` underwent a significant change in version 3.0.0 to support multi-app configurations. If upgrading from 2.x, existing single-app configurations might need to be wrapped in a 'default' key or adjusted for the new structure.
- breaking The default development server port changed from 3000 to 5173 in version 3.0.1 to align with Vite 3/4 defaults. Projects upgrading from versions prior to 3.0.1 that relied on the default port will need to update their Vite dev server configuration or explicitly set `DJANGO_VITE['default']['dev_server_port'] = 3000` (or your preferred port).
- gotcha The `manifest_path` is critical and must accurately point to the `manifest.json` file generated by Vite during the build process. The default may not match your project structure, leading to `FileNotFoundError` in production.
- gotcha For Hot Module Replacement (HMR) to function correctly in development, the `{% vite_hmr_client %}` template tag must be placed *before* any `{% vite_asset %}` tags in your HTML.
- gotcha When running `collectstatic` for deployment, Vite-built assets (including `manifest.json`) are typically not included by default. This can lead to production issues where `django-vite` cannot find its required manifest file.
Install
-
pip install django-vite
Imports
- DjangoViteConfig
INSTALLED_APPS = ['django_vite']
- vite_asset
{% load django_vite %} {% vite_asset 'main.js' %} - vite_hmr_client
{% load django_vite %} {% vite_hmr_client %}
Quickstart
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
INSTALLED_APPS = [
# ... other apps
'django_vite',
]
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') # For collectstatic
# Vite configuration
DJANGO_VITE = {
'default': {
'build_dir': os.path.join(BASE_DIR, 'static', '.vite'),
'manifest_path': os.path.join(BASE_DIR, 'static', '.vite', 'manifest.json'),
'dev_server_url': 'http://localhost:5173',
'static_url_prefix': '/static/', # Must match STATIC_URL for production
}
}
# In your template (e.g., templates/base.html):
# {% load django_vite %}
# <!DOCTYPE html>
# <html lang="en">
# <head>
# <meta charset="UTF-8">
# <meta name="viewport" content="width=device-width, initial-scale=1.0">
# <title>My Django Vite App</title>
# {% vite_hmr_client %}
# {% vite_asset 'src/main.js' %}
# </head>
# <body>
# <div id="app"></div>
# </body>
# </html>