diff --git a/django_vite/templatetags/django_vite.py b/django_vite/templatetags/django_vite.py index 56dcec0..6e18ddb 100644 --- a/django_vite/templatetags/django_vite.py +++ b/django_vite/templatetags/django_vite.py @@ -4,6 +4,7 @@ from urllib.parse import urljoin from django import template +from django.apps import apps from django.conf import settings from django.utils.safestring import mark_safe @@ -138,7 +139,9 @@ def generate_vite_asset( # Add the script by itself tags.append( DjangoViteAssetLoader._generate_script_tag( - urljoin(DJANGO_VITE_STATIC_URL, manifest_entry["file"]), + DjangoViteAssetLoader._generate_production_server_url( + manifest_entry["file"] + ), attrs=scripts_attrs, ) ) @@ -173,11 +176,14 @@ def _generate_css_files_of_asset( if "css" in manifest_entry: for css_path in manifest_entry["css"]: if css_path not in already_processed: - tags.append( - DjangoViteAssetLoader._generate_stylesheet_tag( - urljoin(DJANGO_VITE_STATIC_URL, css_path) + url = ( + DjangoViteAssetLoader._generate_production_server_url( + css_path ) ) + tags.append( + DjangoViteAssetLoader._generate_stylesheet_tag(url) + ) already_processed.append(css_path) @@ -208,7 +214,9 @@ def generate_vite_asset_url(self, path: str) -> str: f"at {DJANGO_VITE_MANIFEST_PATH}" ) - return urljoin(DJANGO_VITE_STATIC_URL, self._manifest[path]["file"]) + return DjangoViteAssetLoader._generate_production_server_url( + self._manifest[path]["file"] + ) def generate_vite_legacy_polyfills( self, @@ -240,7 +248,9 @@ def generate_vite_legacy_polyfills( for path, content in self._manifest.items(): if DJANGO_VITE_LEGACY_POLYFILLS_MOTIF in path: return DjangoViteAssetLoader._generate_script_tag( - urljoin(DJANGO_VITE_STATIC_URL, content["file"]), + DjangoViteAssetLoader._generate_production_server_url( + content["file"] + ), attrs=scripts_attrs, ) @@ -288,7 +298,9 @@ def generate_vite_legacy_asset( scripts_attrs = {"nomodule": "", "crossorigin": "", **kwargs} return DjangoViteAssetLoader._generate_script_tag( - urljoin(DJANGO_VITE_STATIC_URL, manifest_entry["file"]), + DjangoViteAssetLoader._generate_production_server_url( + manifest_entry["file"] + ), attrs=scripts_attrs, ) @@ -428,6 +440,27 @@ def generate_vite_react_refresh_url(cls) -> str: window.__vite_plugin_react_preamble_installed__ = true """ + @staticmethod + def _generate_production_server_url(path: str) -> str: + """ + Generates an URL to an asset served during production. + + Keyword Arguments: + path {str} -- Path to the asset. + + Returns: + str -- Full URL to the asset. + """ + + if apps.is_installed("django.contrib.staticfiles"): + from django.contrib.staticfiles.storage import staticfiles_storage + + return staticfiles_storage.url( + urljoin(DJANGO_VITE_STATIC_URL_PREFIX, path) + ) + else: + return urljoin(DJANGO_VITE_STATIC_URL_PREFIX, path) + # Make Loader instance at startup to prevent threading problems DjangoViteAssetLoader.instance()