Django Vite Plugin

repository·master·Indexed 41 days ago

https://github.com/protibimbok/django-vite-plugin

Integration between Django and Vite (version 4.1.2) that enables Hot Module Replacement (HMR) during development and optimized asset builds for production. It provides a Django template tag for injecting assets, automatic static file path resolution, and JavaScript import aliases for project roots and app directories.

Tokens
8.4K
Snippets
30
Records
36
Agent score
95%

What's inside Django Vite Plugin

  1. Available Example Configurations

    master

    The repository includes several example projects demonstrating different integration patterns:

    ExampleDescription
    outputBasic setup with Tailwind CSS and multiple apps
    reactReact integration with TypeScript
    multi_appMultiple Django apps with separate static files
    custom_buildCustom build output directory configuration
    svelte-in-different-dirSvelte with Vite config in a separate frontend directory
    stderrEdge case and error handling tests
  2. Use import aliases in JavaScript

    master

    The plugin provides convenient import aliases that can be used in your JavaScript files. When you run npm run dev, the plugin automatically updates your jsconfig.json or tsconfig.json to enable IDE autocomplete for these aliases.

    AliasResolves To
    @Project root
    @s:myappmyapp/static/myapp/
    @t:myappmyapp/templates/myapp/
    // Import from your app's static folder
    import utils from '@s:myapp/js/utils.js'
    
    // Import from templates (useful for React/Vue components)
    import App from '@t:myapp/App.jsx'
  3. How static file lookup and path resolution works

    master

    The plugin simplifies asset paths by automatically resolving them using Django's static file finders. If you follow the Django convention of placing files in app_name/static/app_name/, you can use shorter paths in your templates.

    Input PathResolved Path
    myapp/script.jsmyapp/static/myapp/script.js
    myapp/static/script.jsmyapp/static/script.js
    static/script.jsstatic/script.js
  4. Deploy to production

    master

    To prepare for production, follow these steps:

    Standard Deployment

    1. Run npm run build to generate the production assets.
    2. Run python manage.py collectstatic to collect the built assets.
    3. Ensure DEBUG = False in your Django settings (or explicitly set DEV_MODE: False in DJANGO_VITE_PLUGIN).

    CDN / External Static Server

    If hosting assets on a CDN, configure BUILD_URL_PREFIX in your Django settings:

    DJANGO_VITE_PLUGIN = {
        'DEV_MODE': False,
        'BUILD_URL_PREFIX': 'https://cdn.example.com/static/',
    }

    Note: The manifest file must remain accessible locally at BUILD_DIR/.vite/manifest.json so the plugin can resolve asset names.

  5. Manual Setup of Example Projects

    master

    If you want to configure the environment manually instead of using the setup script, follow these steps:

    1. Install the Django package: Navigate to the django directory and install it in editable mode.
    2. Build the Vite plugin: Navigate to the vite directory, install dependencies, and run the build.
    3. Install example dependencies: Navigate to the specific example directory (e.g., example/output) and install dependencies.
    4. Run the servers: You must run both the Django development server and the Vite development server in separate terminals.
    # 1. Install Django package
    cd django
    pip install -e .
    
    # 2. Build Vite plugin
    cd vite
    pnpm install
    pnpm build
    
    # 3. Install example dependencies
    cd example/output
    pnpm install
    
    # 4. Run servers
    # Terminal 1
    python manage.py runserver
    
    # Terminal 2
    pnpm dev
  6. Use Vite in Django templates

    master

    To integrate Vite assets into your Django templates, follow these steps:

    1. Load the vite template tag using {% load vite %}.
    2. Use {% vite %} (without arguments) to inject the Vite development client for Hot Module Replacement (HMR). This will not be rendered in production.
    3. Use {% vite 'path/to/asset.css' 'path/to/asset.js' ... %} to render specific assets. You can pass additional attributes as keyword arguments.
    {% load vite %}
    <!DOCTYPE html>
    <html lang="en">
        <head>
            <!-- Vite dev client for hmr (will not be displayed on production) -->
            {% vite %}
            
            <!-- Renders specific assets with custom attributes -->
            {% vite 'asset1.css' 'asset2.js' someattr='value' %}
        </head>
        <body>
            <!-- Page content -->
        </body>
    </html>
  7. Preserve component state during HMR

    master

    Hot Module Replacement (HMR) in Svelte may not preserve local component state due to the default configuration of svelte-hmr and @sveltejs/vite-plugin-svelte. To ensure important data is retained during development, use an external Svelte store instead of local component state.

    // store.ts
    // An extremely simple external store
    import { writable } from 'svelte/store'
    export default writable(0)
  8. Test with the Published npm Package

    master

    By default, examples link to the local Vite plugin. To test your integration using the published npm package:

    1. Update your package.json to use the official version (e.g., "django-vite-plugin": "^4.1.0").
    2. Run your package manager's install command (pnpm install or npm install).
    3. Build the frontend and start the Django server.
    // package.json
    {
      "dependencies": {
        "django-vite-plugin": "^4.1.0"
      }
    }
  9. Add React-specific lint rules using eslint-plugin-react-x

    master

    To add specialized React and React DOM linting, install eslint-plugin-react-x and eslint-plugin-react-dom, then register them as plugins in your eslint.config.js. You can then spread their recommended rule sets into your configuration.

    import reactX from 'eslint-plugin-react-x'
    import reactDom from 'eslint-plugin-react-dom'
    
    export default tseslint.config({
      plugins: {
        'react-x': reactX,
        'react-dom': reactDom,
      },
      rules: {
        // Enable recommended rules
        ...reactX.configs['recommended-typescript'].rules,
        ...reactDom.configs.recommended.rules,
      },
    })
  10. Quick Start Guide

    master

    Follow these four steps to set up a basic integration:

    1. Configure Django: Add 'django_vite_plugin' to your INSTALLED_APPS in settings.py.
    2. Configure Vite: Create a vite.config.js and add djangoVitePlugin to the plugins array, passing your entry points (JS and CSS files).
    3. Use in Templates: Load the vite template tag and use {% vite %} to load the HMR client, then {% vite 'path/to/asset' %} for your specific files.
    4. Run Servers: Run python manage.py runserver in one terminal and npm run dev in another.
    # 1. settings.py
    INSTALLED_APPS = [
        # ...
        'django_vite_plugin',
    ]
    // 2. vite.config.js
    import { defineConfig } from 'vite'
    import { djangoVitePlugin } from 'django-vite-plugin'
    
    export default defineConfig({
        plugins: [
            djangoVitePlugin([
                'myapp/js/main.js',
                'myapp/css/styles.css',
            ])
        ],
    })
    {# 3. template.html #}
    {% load vite %}
    <!DOCTYPE html>
    <html lang="en">
    <head>
        {% vite %}
        {% vite 'myapp/js/main.js' 'myapp/css/styles.css' %}
    </head>
    <body>
    </body>
    </html>
    # 4. Terminal commands
    python manage.py runserver
    npm run dev