DjangoCon Europe 2019: Take the goRe out of a DjangoReact stack
Writeup of the DjangoCon Europe 2019 talk »Take the goRe out of a DjangoReact stack« by Nathan Gaberel
Nathan Gaberel: An architect at Theodo, working with startups to launch MVPs and large corporates to deliver at startup speed. Co-founded the React Native London meetup, has been a speaker at a few javascript meetups in London and maintains the redux-saga-firebase package.
JS Toolchain notes
npm is basically pypi and pip, and webpack handles all the remaining magic – especially complex buildchains are usually completely managed via webpack.
History
Way back when Django was released, JS just made pages a bit nicer. Or uglier. Many years later, django-pipeline and django-compressor were released, to aid with generating proper bundled static files. Yet many years later, JS frameworks started to take off, and webpack was created for them.
Then there was django-webpack-loader
, which basically runs webpack, and provides a script tag for django to include.
Modes of operation
You'll also want to look at this blog series by Aymeric Augustin on this topic, which talks about the use case of having different frontend and API servers at different locations, talking to each other.
The counterpart of this model is the hybrid application, where both the Django output and the Javascript output are sent to the browser by a single point of contact.
Designing Django+JS architecture
Environment independent builds
Trust that what works in staging will also work in production. This is pretty easy to do – do not hardcode variables, read environment variables instead. Django is good at this. Often-used values for this would be the main endpoint, which is different in development than in production, naturally.
JS doesn#t have a concept of this, so we either have to make API calls, or inject the values with Django in rendering. (Side note: Webpack of course supports environment variables.)
Hot reloading in development
Shorter feedback loops significantly aids development.
This relies on Webpack Dev Server – live reloading refreshes the full page, and hot reloading just replaces changed code in-place via websocket updates.
For this, static files are going to be listed in Django as coming from the WebPack dev server, which then provides the updates.
Dev/prod parity
Render the same code in development and production, so no {% if debug %}
in your templates.
django-webpack-loader
provides a render_bundle
template tag which provides a saner template environment.
So in the end, static files and updates are coming from the webpack server, and templates including script tags come from Django. WebPack will output a manifest via the BundleTrackerPlugin, which Django then can use to keep track of the static files.