django-vite
django-vite copied to clipboard
Disable staticfiles.storage to generate URLs
Staticfiles serving was implemented to leverage Django's new support_js_module_import_aggregation.
But I think it is not production ready yet. On my projects it is not working either.
Next, without support_js_module_import_aggregation
it could be very dangerous to provide 2 versions of JS module.
Assume this scenario:
-
django-vite
providesentrypoint.<vitehash>.<djangohash>
- Entrypoint imports more modules
- One of these modules imports entrypoint (circular). But, the reference is without
djangohash
becasue files were not processed by Django. So the entrypoint is re-evaluated and our app crash.
I think static files should be used only with support_js_module_import_aggregation
. So it make sense to introduce something like DJANGO_VITE_USE_STATICFILES
to be able to control it. Or even better to check if STATICFILES_STORAGE
has enabled support_js_module_import_aggregation
?
Btw. compression works in whitenoise
even if the file is served directly as original, entrypoint.<vitehash>
in our case.
@petrprikryl Thank you for addressing this issue. I ran into this problem during development of an inertia.js application. As you mentioned the entrypoint was requested via main.<vitehash>.<djangohash>
but the first page / component got lazy loaded and also imported this main file. But, this import did not contain the djangohash so it ran the main file again.
This resulted in very unclear errors in my application and I couldn't figure out why. Eventually I noticed the main file twice in the request tab of the browser console.
After I found this issue I tried the support_js_module_import_aggregation
setting as well, but unfortunately this does not work in my case. My solution for now is to downgrade to version 2.0.2.
I like your suggestion to control this feature via a setting. Maybe it should even be disabled by default when the ManifestStaticFilesStorage
is used.
Eventually solved this by adding a custom url
definition to the storage class.
class ManifestStaticFilesStorage(ManifestFilesMixin, GoogleCloudStorage):
vite_hash_pattern = r"^.+[\.-][0-9a-zA-Z_-]{8,12}\..+$"
def url(self, name, force=False):
# if the file already has a hash, we don't need the django hashed file
if re.match(self.vite_hash_pattern, name):
return super(HashedFilesMixin, self).url(name)
return super().url(name, force)
I came up with a solution similar to @svengt, but this way skips hashing the vite files alltogether (based on https://github.com/TomAnthony/django-flexible-manifest-staticfiles):
(in our case all vite output is identifiable by the directory it's stored in, so no need for a regex)
def _is_excluded(name):
return name.startswith("vite/")
class SelectiveManifestStaticFilesStorage(ManifestStaticFilesStorage):
def hashed_name(self, name, content=None, filename=None):
if _is_excluded(name):
return name
else:
return super().hashed_name(name, content, filename)