CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-django-vite

Integration of Vite in a Django project.

Pending
Overview
Eval results
Files

template-tags.mddocs/

Template Tags

Django template tags for integrating Vite assets into Django templates, supporting both development and production modes with HMR, React refresh, and legacy browser compatibility.

Usage

Load the template tags in your Django templates:

{% load django_vite %}

All template tags support the app parameter for multi-app configurations (defaults to "default").

Capabilities

Asset Inclusion

Include Vite-managed JavaScript and TypeScript assets with automatic CSS dependencies and module preloading.

def vite_asset(path: str, app: str = "default", **kwargs) -> str:
    """
    Generate script tag for JS/TS asset with CSS dependencies and modulepreload tags.
    
    Args:
        path: Path to Vite JS/TS asset to include
        app: Configuration app name (default: "default")
        **kwargs: Additional attributes for generated script tags
        
    Returns:
        HTML string with script and link tags
        
    Raises:
        DjangoViteAssetNotFoundError: If asset not found in manifest (production only)
    """

Basic Usage:

{% vite_asset 'src/main.js' %}

With Custom Attributes:

{% vite_asset 'src/app.js' defer=True data-module="app" %}

Multi-App Usage:

{% vite_asset 'src/admin.js' app='admin' %}

Development Mode Output:

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

Production Mode Output:

<link rel="stylesheet" href="/static/assets/main.abc123.css" />
<script type="module" crossorigin src="/static/assets/main.def456.js"></script>
<link href="/static/assets/vendor.789xyz.js" type="text/javascript" crossorigin="anonymous" rel="modulepreload" as="script" />

Asset URL Generation

Generate URLs for Vite-managed assets without including dependencies.

def vite_asset_url(path: str, app: str = "default") -> str:
    """
    Generate URL for a Vite-managed asset.
    
    Args:
        path: Path to Vite asset
        app: Configuration app name (default: "default")
        
    Returns:
        URL string for the asset
        
    Raises:
        DjangoViteAssetNotFoundError: If asset not found in manifest (production only)
    """

Usage:

<img src="{% vite_asset_url 'src/images/logo.png' %}" alt="Logo">

Output (Development):

<img src="http://localhost:5173/static/src/images/logo.png" alt="Logo">

Output (Production):

<img src="/static/assets/logo.abc123.png" alt="Logo">

Asset Preloading

Generate modulepreload and preload tags for performance optimization.

def vite_preload_asset(path: str, app: str = "default") -> str:
    """
    Generate modulepreload tags for JS/TS asset and dependencies.
    
    Args:
        path: Path to Vite JS/TS asset to preload
        app: Configuration app name (default: "default")
        
    Returns:
        HTML string with preload link tags (empty in development)
        
    Raises:
        DjangoViteAssetNotFoundError: If asset not found in manifest (production only)
    """

Usage:

<head>
    {% vite_preload_asset 'src/main.js' %}
    {% vite_asset 'src/main.js' %}
</head>

Output (Production):

<link href="/static/assets/main.def456.js" type="text/javascript" crossorigin="anonymous" rel="modulepreload" as="script" />
<link href="/static/assets/main.abc123.css" rel="preload" as="style" />
<link href="/static/assets/vendor.789xyz.js" type="text/javascript" crossorigin="anonymous" rel="modulepreload" as="script" />

Hot Module Replacement Client

Include Vite's HMR client for development mode with live reloading.

def vite_hmr_client(app: str = "default", **kwargs) -> str:
    """
    Generate script tag for Vite WebSocket client for HMR.
    
    Args:
        app: Configuration app name (default: "default")
        **kwargs: Additional attributes for generated script tag
        
    Returns:
        Script tag HTML (empty string in production)
    """

Usage:

<head>
    {% vite_hmr_client %}
</head>

Output (Development):

<script type="module" src="http://localhost:5173/@vite/client"></script>

Output (Production):

<!-- Empty string -->

With Custom Attributes:

{% vite_hmr_client data-turbo-track="reload" %}

React Refresh

Include React refresh runtime for React HMR support.

def vite_react_refresh(app: str = "default", **kwargs) -> str:
    """
    Generate script for Vite React Refresh runtime for HMR.
    
    Args:
        app: Configuration app name (default: "default")
        **kwargs: Additional attributes for generated script tags
        
    Returns:
        Inline script HTML (empty string in production)
    """

Usage:

<head>
    {% vite_react_refresh %}
</head>

Output (Development):

<script type="module">
    import RefreshRuntime from 'http://localhost:5173/@react-refresh'
    RefreshRuntime.injectIntoGlobalHook(window)
    window.$RefreshReg$ = () => {}
    window.$RefreshSig$ = () => (type) => type
    window.__vite_plugin_react_preamble_installed__ = true
</script>

Legacy Browser Support

Support legacy browsers using @vitejs/plugin-legacy generated polyfills and assets.

def vite_legacy_polyfills(app: str = "default", nomodule: bool = True, **kwargs) -> str:
    """
    Generate script tag for legacy browser polyfills.
    
    Args:
        app: Configuration app name (default: "default")
        nomodule: Set nomodule attribute (default: True)
        **kwargs: Additional attributes for generated script tag
        
    Returns:
        Script tag HTML (empty string in development)
        
    Raises:
        DjangoViteAssetNotFoundError: If polyfills not found in manifest
    """

Usage:

<body>
    {% vite_legacy_polyfills %}
    <!-- Other legacy scripts -->
</body>

Output (Production):

<script crossorigin nomodule src="/static/assets/polyfills-legacy.abc123.js"></script>

Without nomodule attribute:

{% vite_legacy_polyfills nomodule=False %}

Legacy Asset Inclusion

Include legacy versions of assets for older browsers.

def vite_legacy_asset(path: str, app: str = "default", **kwargs) -> str:
    """
    Generate script tag for legacy asset versions.
    
    Args:
        path: Path to legacy Vite asset (must contain '-legacy' in name)
        app: Configuration app name (default: "default")
        **kwargs: Additional attributes for generated script tag
        
    Returns:
        Script tag HTML (empty string in development)
        
    Raises:
        DjangoViteAssetNotFoundError: If legacy asset not found in manifest
    """

Usage:

{% vite_legacy_asset 'src/main-legacy.js' %}

Output (Production):

<script nomodule crossorigin src="/static/assets/main-legacy.def456.js"></script>

Template Tag Examples

Complete Template Setup

{% load django_vite %}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>My Django App</title>
    
    <!-- Preload critical assets -->
    {% vite_preload_asset 'src/main.js' %}
    
    <!-- HMR client for development -->
    {% vite_hmr_client %}
    
    <!-- React refresh for development -->
    {% vite_react_refresh %}
    
    <!-- Main application assets -->
    {% vite_asset 'src/main.js' %}
</head>
<body>
    <div id="app"></div>
    
    <!-- Legacy browser support -->
    {% vite_legacy_polyfills %}
    {% vite_legacy_asset 'src/main-legacy.js' %}
</body>
</html>

Multi-App Template

{% load django_vite %}
<!DOCTYPE html>
<html>
<head>
    <!-- Frontend app -->
    {% vite_hmr_client app='frontend' %}
    {% vite_asset 'src/main.js' app='frontend' %}
    
    <!-- Admin app -->
    {% vite_hmr_client app='admin' %}
    {% vite_asset 'src/admin.js' app='admin' %}
</head>
<body>
    <div id="frontend-app"></div>
    <div id="admin-panel"></div>
</body>
</html>

Custom Attributes Example

{% load django_vite %}

<!-- Defer script loading -->
{% vite_asset 'src/analytics.js' defer=True %}

<!-- Add data attributes -->
{% vite_asset 'src/app.js' data-version="1.0" data-env="production" %}

<!-- Custom CSS media queries -->
{% vite_asset 'src/print.css' media="print" %}

Error Handling

Template tags raise DjangoViteAssetNotFoundError in production when assets are missing from the manifest. This typically occurs when:

  • Asset path doesn't match entries in manifest.json
  • Manifest file is missing or corrupted
  • Asset was not included in Vite build

Debug Missing Assets:

# In views or management commands
from django_vite.core.asset_loader import DjangoViteAssetLoader

loader = DjangoViteAssetLoader.instance()
try:
    asset_html = loader.generate_vite_asset('src/missing.js')
except DjangoViteAssetNotFoundError as e:
    print(f"Asset not found: {e}")
    # Check manifest or Vite build configuration

Install with Tessl CLI

npx tessl i tessl/pypi-django-vite

docs

asset-loading.md

configuration.md

index.md

template-tags.md

tile.json