{"id":14977021,"url":"https://github.com/mrbin99/django-vite","last_synced_at":"2025-05-14T03:05:50.007Z","repository":{"id":37914367,"uuid":"354076059","full_name":"MrBin99/django-vite","owner":"MrBin99","description":"Integration of ViteJS in a Django project.","archived":false,"fork":false,"pushed_at":"2024-09-16T13:41:28.000Z","size":184,"stargazers_count":566,"open_issues_count":26,"forks_count":72,"subscribers_count":13,"default_branch":"master","last_synced_at":"2024-10-29T15:19:15.188Z","etag":null,"topics":["django","python","vite","vitejs"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/MrBin99.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-04-02T16:38:45.000Z","updated_at":"2024-10-26T17:22:45.000Z","dependencies_parsed_at":"2023-12-06T21:31:00.703Z","dependency_job_id":"c53061f2-5539-48bd-a580-3f111572c647","html_url":"https://github.com/MrBin99/django-vite","commit_stats":{"total_commits":59,"total_committers":5,"mean_commits":11.8,"dds":"0.18644067796610164","last_synced_commit":"dd8152b428c78883e4617ab7e5c907539197afb6"},"previous_names":[],"tags_count":24,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MrBin99%2Fdjango-vite","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MrBin99%2Fdjango-vite/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MrBin99%2Fdjango-vite/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MrBin99%2Fdjango-vite/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/MrBin99","download_url":"https://codeload.github.com/MrBin99/django-vite/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248388451,"owners_count":21095392,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["django","python","vite","vitejs"],"created_at":"2024-09-24T13:54:53.507Z","updated_at":"2025-05-14T03:05:49.993Z","avatar_url":"https://github.com/MrBin99.png","language":"Python","readme":"# Django Vite\n\n[![PyPI version](https://badge.fury.io/py/django-vite.svg)](https://badge.fury.io/py/django-vite)\n\nIntegration of [ViteJS](https://vitejs.dev/) in a Django project.\n\n- [Installation](#installation)\n  - [Django](#django)\n  - [ViteJS](#vitejs)\n  - [Assets](#assets)\n- [Usage](#usage)\n  - [Configuration](#configuration)\n  - [Dev Mode](#dev-mode)\n  - [Template tags](#template-tags)\n  - [Custom attributes](#custom-attributes)\n  - [Loading assets from a CDN](#loading-assets-from-a-cdn)\n- [Vite Legacy Plugin](#vite-legacy-plugin)\n- [Multi-app configuration](#multi-app-configuration)\n- [Configuration Variables](#configuration-variables)\n  - [dev\\_mode](#dev_mode)\n  - [dev\\_server\\_protocol](#dev_server_protocol)\n  - [dev\\_server\\_host](#dev_server_host)\n  - [dev\\_server\\_port](#dev_server_port)\n  - [static\\_url\\_prefix](#static_url_prefix)\n  - [manifest\\_path](#manifest_path)\n  - [legacy\\_polyfills\\_motif](#legacy_polyfills_motif)\n  - [ws\\_client\\_url](#ws_client_url)\n  - [react\\_refresh\\_url](#react_refresh_url)\n  - [app\\_client\\_class](#app_client_class)\n- [Notes](#notes)\n  - [Whitenoise](#whitenoise)\n- [Examples](#examples)\n- [Thanks](#thanks)\n\n\n## Installation\n\n### Django\n\n```\npip install django-vite\n```\n\nAdd `django_vite` to your `INSTALLED_APPS` in your `settings.py`\n(before your apps that are using it).\n\n```python\nINSTALLED_APPS = [\n    ...\n    'django_vite',\n    ...\n]\n```\n\n### ViteJS\n\nFollow instructions on [https://vitejs.dev/guide/](https://vitejs.dev/guide/).\nAnd mostly the SSR part.\n\nThen in your ViteJS config file :\n\n- Set the `base` options the same as your `STATIC_URL` Django setting.\n- Set the `build.outDir` path to where you want the assets to compiled.\n- Set the `build.manifest` options to `manifest.json`.\n- As you are in SSR and not in SPA, you don't have an `index.html` that\n  ViteJS can use to determine which files to compile. You need to tell it\n  directly in `build.rollupOptions.input`.\n\n```javascript\nexport default defineConfig({\n  ...\n  base: \"/static/\",\n  build: {\n    ...\n    manifest: \"manifest.json\",\n    outDir: resolve(\"./assets\"),\n    rollupOptions: {\n      input: {\n        \u003cunique key\u003e: '\u003cpath to your asset\u003e'\n      }\n    }\n  }\n})\n```\n\n### Assets\n\nAs recommended on Vite's [backend integration guide](https://vitejs.dev/guide/backend-integration.html), your assets should include the modulepreload polyfill.\n\n```javascript\n// Add this at the beginning of your app entry.\nimport 'vite/modulepreload-polyfill';\n```\n\n## Usage\n\n### Configuration\n\nDefine a default `DJANGO_VITE` configuration in your `settings.py`.\n\n```python\nDJANGO_VITE = {\n  \"default\": {\n    \"dev_mode\": True\n  }\n}\n```\n\nOr if you prefer to use the legacy module-level settings, you can use:\n\n```python\nDJANGO_VITE_DEV_MODE = True\n```\n\nBe sure that the `build.outDir` from `vite.config.js` is included in `STATICFILES_DIRS`.\n\n```python\nSTATICFILES_DIRS = [\n  BASE_DIR / \"assets\"\n]\n```\n\n### Dev Mode\n\nThe `dev_mode`/`DJANGO_VITE_DEV_MODE` boolean defines if you want to include assets in development mode or production mode.\n- In development mode, assets are included as modules using the ViteJS\n  webserver. This will enable HMR for your assets.\n- In production mode, assets are included as standard assets\n  (no ViteJS webserver and HMR) like default Django static files.\n  This means that your assets must be compiled with ViteJS before.\n- This setting may be set as the same value as your `DEBUG` setting in\n  Django. But you can do what is good for your needs.\n\n### Template tags\n\nInclude this in your base HTML template file.\n\n```\n{% load django_vite %}\n```\n\nThen in your `\u003chead\u003e` element add this :\n\n```\n{% vite_hmr_client %}\n```\n\n- This will add a `\u003cscript\u003e` tag to include the ViteJS HMR client.\n- This tag will include this script only if `DJANGO_VITE_DEV_MODE` is true,\n  otherwise this will do nothing.\n\nThen add this tag (in your `\u003chead\u003e` element too) to load your scripts :\n\n```\n{% vite_asset '\u003cpath to your asset\u003e' %}\n```\n\nThis will add a `\u003cscript\u003e` tag including your JS/TS script :\n\n- In development and production, all scripts are included as modules (`[type=module]`).\n- You can pass a second argument to this tag to overrides attributes\n  passed to the script tag.\n- This tag only accept JS/TS, for other type of assets, they must be\n  included in the script itself using `import` statements.\n- In production mode, the library will read the `manifest.json` file\n  generated by ViteJS and import all CSS files dependent of this script\n  (before importing the script).\n- You can add as many of this tag as you want, for each input you specify\n  in your ViteJS configuration file.\n- The path must be relative to your `root` key inside your ViteJS config file.\n- The path must be a key inside your manifest file `manifest.json` file\n  generated by ViteJS.\n  - Alternatively, the path can be an asset name (e.g. `\"name\": \"foo\"` in your manifest).\n    If you set up multiple entrypoints (`build.rollupOptions.input`) in your Vite config,\n    e.g. by following [the Multi-Page App](https://vite.dev/guide/build.html#multi-page-app)\n    docs, this would be the key in the entrypoint object.\n- In general, this path does not require a `/` at the beginning\n  (follow your `manifest.json` file).\n\n```\n{% vite_asset_url '\u003cpath to your asset\u003e' %}\n```\n\nThis will generate only the URL to an asset with no tag surrounding it.\n**Warning, this does not generate URLs for dependant assets of this one\nlike the previous tag.**\n\n```\n{% vite_react_refresh %}\n```\nIf you're using React, this will generate the Javascript `\u003cscript/\u003e` needed to support React HMR.\n\n```\n{% vite_react_refresh nonce=\"{{ request.csp_nonce }}\" %}\n```\n\nAny kwargs passed to vite_react_refresh will be added to its generated `\u003cscript/\u003e` tag. For example, if your site is configured with a Content Security Policy using [django-csp](https://github.com/mozilla/django-csp) you'll want to add this value for `nonce`.\n\n### Custom attributes\n\nBy default, all script tags are generated with a `type=\"module\"` and `crossorigin=\"\"` attributes just like ViteJS do by default if you are building a single-page app.\nYou can override this behavior by adding or overriding this attributes like so :\n\n```jinja-html\n{% vite_asset '\u003cpath to your asset\u003e' foo=\"bar\" hello=\"world\" data_turbo_track=\"reload\" %}\n```\n\nThis line will add `foo=\"bar\"`, `hello=\"world\"`, and `data-turbo-track=\"reload\"` attributes.\n\nYou can also use context variables to fill attributes values :\n\n```\n{% vite_asset '\u003cpath to your asset\u003e' foo=request.GET.bar %}\n```\n\nIf you want to overrides default attributes just add them like new attributes :\n\n```\n{% vite_asset '\u003cpath to your asset\u003e' crossorigin=\"anonymous\" %}\n```\n\nAlthough it's recommended to keep the default `type=\"module\"` attribute as ViteJS build scripts as ES6 modules.\n\n### Loading assets from a CDN\n\nBy default, django-vite will try to load a local `manifest.json`.\n\nIf you want django-vite to fetch the manifest from a non-standard source like S3, you can subclass DjangoViteAppClient and override its ManifestClient. Below is a minimal example:\n\n```python\n# myapp/django_vite_s3.py\nimport json\nimport boto3\nfrom django_vite.core.asset_loader import ManifestClient, DjangoViteAppClient\n\nclass S3ManifestClient(ManifestClient):\n    def load_manifest(self):\n        s3 = boto3.client(\"s3\")\n        res = s3.get_object(Bucket='django-vite-public-example', Key='manifest.json')\n        manifest_content = res[\"Body\"].read()\n        return json.loads(manifest_content)\n\nclass S3DjangoViteAppClient(DjangoViteAppClient):\n    ManifestClient = S3ManifestClient\n```\n\nThen configure your app to use your custom `S3DjangoViteAppClient`:\n\n```python\n# settings.py\nfrom django_vite.core.asset_loader import DjangoViteConfig\n\nDJANGO_VITE = {\n    \"default\": DjangoViteConfig(\n        dev_mode=False,\n        app_client_class=\"myapp.django_vite_s3.S3DjangoViteAppClient\",\n        ...\n    )\n}\n```\n\nIf your \"django.contrib.staticfiles\" is configured to use S3, then your assets should load properly without needing further configuration.\n\nSince this feature support is a new work-in-progress, please share with the community any configurations that have worked well for you!\n\nIf you find yourself needing greater control over how static asset urls are rendered, you can modify `DjangoViteAppClient.get_production_server_url`:\n\n```python\n# myapp/django_vite_s3.py\nimport json\nimport boto3\nfrom django_vite.core.asset_loader import ManifestClient, DjangoViteAppClient\n\nclass S3ManifestClient(ManifestClient):\n    def load_manifest(self):\n        s3 = boto3.client(\"s3\")\n        res = s3.get_object(Bucket='django-vite-public-example', Key='manifest.json')\n        manifest_content = res[\"Body\"].read()\n        return json.loads(manifest_content)\n\nclass S3DjangoViteAppClient(DjangoViteAppClient):\n    ManifestClient = S3ManifestClient\n\n    def get_production_server_url(self, path: str) -\u003e str:\n        # Make additional charge here as needed\n        ...\n```\n\n## Vite Legacy Plugin\n\nIf you want to consider legacy browsers that don't support ES6 modules loading\nyou may use [@vitejs/plugin-legacy](https://github.com/vitejs/vite/tree/main/packages/plugin-legacy).\nDjango Vite supports this plugin. You must add stuff in complement of other script imports in the `\u003chead\u003e` tag.\n\nJust before your `\u003cbody\u003e` closing tag add this :\n\n```\n{% vite_legacy_polyfills %}\n```\n\nThis tag will do nothing in development, but in production it will loads the polyfills\ngenerated by ViteJS.\n\nAnd so next to this tag you need to add another import to all the scripts you have\nin the head but the 'legacy' version generated by ViteJS like so :\n\n```\n{% vite_legacy_asset '\u003cpath to your asset\u003e' %}\n```\n\nLike the previous tag, this will do nothing in development but in production,\nDjango Vite will add a script tag with a `nomodule` attribute for legacy browsers.\nThe path to your asset must contain de pattern `-legacy` in the file name (ex : `main-legacy.js`).\n\nThis tag accepts overriding and adding custom attributes like the default `vite_asset` tag.\n\n## Multi-app configuration\n\nIf you would like to use django-vite with multiple vite configurations you can specify them in your settings.\n\n```python\nDJANGO_VITE = {\n  \"default\": {\n    \"dev_mode\": True,\n  },\n  \"external_app_1\": {\n    ...\n  },\n  \"external_app_2\": {\n    ...\n  }\n}\n```\n\nSpecify the app in each django-tag tag that you use in your templates. If no app is provided, it will default to using the \"default\" app.\n\n```html\n{% vite_asset '\u003cpath to your asset\u003e' %}\n{% vite_asset '\u003cpath to another asset\u003e' app=\"external_app_1\" %}\n{% vite_asset '\u003cpath to a third asset\u003e' app=\"external_app_2\" %}\n```\n\nYou can see an example project [here](https://github.com/Niicck/django-vite-multi-app-example).\n\n## Configuration Variables\n\nYou can redefine these values for each app config in `DJANGO_VITE` in `settings.py`.\n\n### dev_mode\n- **Type**: `bool`\n- **Default**: `False`\n- **Legacy Key**: `DJANGO_VITE_DEV_MODE`\n\nIndicates whether to serve assets via the ViteJS development server or from compiled production assets.\n\nRead more: [Dev Mode](#dev-mode)\n\n### dev_server_protocol\n- **Type**: `str`\n- **Default**: `\"http\"`\n- **Legacy Key**: `DJANGO_VITE_DEV_SERVER_PROTOCOL`\n\nThe protocol used by the ViteJS webserver.\n\n### dev_server_host\n- **Type**: `str`\n- **Default**: `\"localhost\"`\n- **Legacy Key**: `DJANGO_VITE_DEV_SERVER_HOST`\n\nThe `server.host` in `vite.config.js` for the ViteJS development server.\n\n### dev_server_port\n- **Type**: `int`\n- **Default**: `5173`\n- **Legacy Key**: `DJANGO_VITE_DEV_SERVER_PORT`\n\nThe `server.port` in `vite.config.js` for the ViteJS development server.\n\n### static_url_prefix\n- **Type**: `str`\n- **Default**: `\"\"`\n- **Legacy Key**: `DJANGO_VITE_STATIC_URL_PREFIX`\n\nThe directory prefix for static files built by ViteJS.\n\n- Use it if you want to avoid conflicts with other static files in your project.\n- It's used in both dev mode and production mode.\n- For dev mode, you also need to add this prefix inside vite config's `base`.\n- For production mode, you may need to add this to vite config's `build.outDir`.\n\nExample:\n\n```python\n# settings.py\nDJANGO_VITE_STATIC_URL_PREFIX = 'bundler'\nSTATICFILES_DIRS = (('bundler', '/srv/app/bundler/dist'),)\n```\n\n```javascript\n// vite.config.js\nexport default defineConfig({\n  base: '/static/bundler/',\n  ...\n})\n```\n\n### manifest_path\n- **Type**: `str | Path`\n- **Default**: `Path(settings.STATIC_ROOT) / static_url_prefix / \"manifest.json\"`\n- **Legacy Key**: `DJANGO_VITE_MANIFEST_PATH`\n\nThe absolute path, including the filename, to the ViteJS manifest file located in `build.outDir`.\n\n### legacy_polyfills_motif\n- **Type**: `str`\n- **Default**: `\"legacy-polyfills\"`\n- **Legacy Key**: `DJANGO_VITE_LEGACY_POLYFILLS_MOTIF`\n\nThe motif used to identify assets for polyfills in the `manifest.json`. This is only applicable if you are using [@vitejs/plugin-legacy](https://github.com/vitejs/vite/tree/main/packages/plugin-legacy).\n\n### ws_client_url\n- **Type**: `str`\n- **Default**: `\"@vite/client\"`\n- **Legacy Key**: `DJANGO_VITE_WS_CLIENT_URL`\n\nThe path to the HMR (Hot Module Replacement) client used in the `vite_hmr_client` tag.\n\n### react_refresh_url\n- **Type**: `str`\n- **Default**: `\"@react-refresh\"\"`\n- **Legacy Key**: `DJANGO_VITE_REACT_REFRESH_URL`\n\nIf you're using React, this will generate the Javascript needed to support React HMR.\n\n### app_client_class\n- **Type**: `str`\n- **Default**: `\"django_vite.core.asset_loader.DjangoViteAppClient\"`\n\nThis is the fully qualified name of a Python class that extends or replaces `DjangoViteAppClient`. This allows you to customize almost any part of django-vite's loader behavior. The most requested reason for adding this feature is customizing how `manifest.json` is loaded.\n\nSee [Loading assets from a CDN](#loading-assets-from-a-cdn) for an example of using a custom class to load the manifest from S3.\n\n## Notes\n\n- In production mode, all generated paths are prefixed with the `STATIC_URL`\n  setting of Django.\n\n### Whitenoise\n\nIf you are serving your static files with whitenoise, by default your files compiled by vite will not be considered immutable and a bad cache-control will be set. To fix this you will need to set a custom test like so:\n\n```python\nimport re\n\n# http://whitenoise.evans.io/en/stable/django.html#WHITENOISE_IMMUTABLE_FILE_TEST\n\ndef immutable_file_test(path, url):\n    # Match vite (rollup)-generated hashes, à la, `some_file-CSliV9zW.js`\n    return re.match(r\"^.+[.-][0-9a-zA-Z_-]{8,12}\\..+$\", url)\n\n\nWHITENOISE_IMMUTABLE_FILE_TEST = immutable_file_test\n```\n\n## Examples\n\nFor examples of how to setup the project in v3, please see [django-vite-examples](https://github.com/Niicck/django-vite-examples).\n\nFor another example that uses the module-level legacy settings, please see this [example project here](https://github.com/MrBin99/django-vite-example).\n\n## Thanks\n\nThanks to [Evan You](https://github.com/yyx990803) for the ViteJS library.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmrbin99%2Fdjango-vite","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmrbin99%2Fdjango-vite","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmrbin99%2Fdjango-vite/lists"}