[Django]-How to load webpack bundle which has content based hash filename as static file in Django?

0👍

The best solution would be to access the webpack configuration file and set the bundle filename to have a static filename. Hashnames based on content for static files are useful for browser caching. However if this is not needed your best bet is probably to eject your create-react-app and tweak the webpack config.

To do with create-react-app this is could be possible to fork the react-scripts module and make such an adjustment.

Another less robust way of doing this if you don’t want to touch the webpack configuration for whatever reason is to create a bash script.

This script goes in the same directory as your package.json and greps the filename of the bundles from the output of the npm run build command. Then copies the css and js bundles to the django static folder under respective css and js directories.

build-django-static.sh

#!/usr/bin/env bash
for bundle in $(npm run build | grep -o 'build\/static\/\S*')
do
  filename=$(basename "$bundle")
  extension="${filename##*.}"
  outputpath=../core/static/${extension}/bundle.${extension}
  cp $bundle $outputpath
  echo copied $bundle to $outputpath
done

Note – It is crucial to change the $outputpath variable to the correct path that points to your static django directory.

Then add a custom npm script to your package.json which calls this bash script.

"scripts": {
   ...
   "build-django-static": "bash ./build-django-static.sh"
   ...
}

Then call the npm script by running the following command from the same directory as your package.json:

npm run build-django-static

3👍

Probably the best option to keep the ‘hashed names’ and avoid cache issues is to use django-webpack-loader and webpack-bundle-tracker.

The first one provides a couple of new tags for the django templates like {% render_bundle 'main' %}. This tag will be replaced at runtime for the path to your bundled main entry point defined in webpack configuration.

The second one is a webpack plugin that ouputs to disk a json file with some information about the bundles like the actual "hashed filename". This json is read by django-webpack-loader to figure out the filenames.

There is a full explantation of how it can be done in this post from the author of both plugins.

For more info you can check these series of posts:

Leave a comment