webpack and django on Heroku: bundling before collectstatic

Viewed 601

I am building a django+react app on Heroku, using django-npm which automatically installs all modules from package.json to node-modules dir and then copies everything to staticfiles/ during python manage.py collectstatic (which is triggered by Heroku during deploy).

However, for this configuration to work I need to pre-bundle my React app before deployment and put it into my static folder along with all the CSS, fonts, etc. to be picked up by collectstatic later.

But I don't want to pollute my git diffs with new bundle versions. So, is there a way to make webpack create a bundle during deployment?

I know there is a release command on Heroku where I can put my npm run build. But the problem is it only fires AFTER collectstatic, so my bundle will only be created in static/ folder after this folder is scanned, and won't get copied to staticfiles dir.

1 Answers

Update: Using bin/pre_compile should no longer be necessary as of March 11, 2019. Heroku will now automatically call an app's build script (if defined in package.json) during Heroku's build process. Source: Heroku Changelog.


Original: You can accomplish this with the (undocumented) pre_compile hook exposed by the heroku/python buildpack.

Add an executable shell file named bin/pre_compile at the top level of your app and it will be called automatically as part of the build process.

cd my-django-app
mkdir bin
echo '#!/usr/bin/env bash' >> bin/pre_compile
echo 'npm run build' >> bin/pre_compile
chmod +x bin/pre_compile
Related