Django: Make JS source maps compatible with staticfiles filename hashing
Asked Answered
A

2

14

In our Django project we are using Gulp to compile our assets, then UglifyJS to minify them. During this whole process we are generating sourcemaps, which appear to be working correctly.

The problem comes when we use the Django static template tag to include our minified files. Say we have a minified JS file called ourapp.min.js. In our template we would write:

<script src="{% static 'ourapp.min.js %}"></script>

which would be compiled into something like:

<script src="/ourstaticroot/ourapp.min.0123456789ab.js"></script>

(where 0123456789ab is a hash of the file contents)

The problem now is that, although the file has been renamed, our sourcemap still points to the old filename, so suddenly becomes invalid. If we then need to debug this page (say, using Sentry) it cannot find the source file and we are left to debug the uglified file instead, which becomes much more of a task.

Does anyone know of a good way to get around this? We would like to continue using Gulp for our assets, and also continue using the hashed filenames, as this prevents issues caused by caching of stale asset files.

Asmodeus answered 22/1, 2016 at 11:5 Comment(3)
if the static tag had an opportunity to work with regexp and you could write something like that {% static 'ourapp\.min\.[0-9a-b]+\.js %}, would it be suitable for your case?Green
Try something like this: github.com/olasitarska/django-gulp-revOnceover
Is your hash coming from gulp minification itself or from ManifestStaticFileStorage?Agonizing
F
1

it does not really matter, since the original files are being kept. So if your file points to a map without a hash it should be served by Django. Of course you need to be careful with long term expiration headers. Should you be using whitenoise are are fine, since they handle expiration properly and long term expiration headers are only set on hashed files.

Cheers -Joe

Frosted answered 22/11, 2018 at 11:4 Comment(0)
D
0

I see two options available to you. It's not clear where exactly the cache busting suffix gets added to your files, but at that point you could:

  • Use some string processing, to manipulate the assets and set their sourceMapUrl with a url that is generated by your system and includes the expected suffix //# sourceMappingURL=/path/to/file.js.<suffix>.map. This could be a simple bash command in a gulp step (if that's where it happens)

  • Alternatively, browsers will also accept an http header SourceMap: /path/to/file.js.map which you could instruct your asset server to set for files with headers. This may be more difficult depending on your infrastructure.

Dogtooth answered 14/4, 2019 at 19:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.