Integrating webpack-dev-server with Django
If you use webpack to build your front-end resources, you can use the optional webpack-dev-server to automatically reload the webpage when your code changes. It’s similar to what you want to accomplish with tools like LiveReload or Browsersync.
The webpack-dev-server uses an Express.js server to serve your bundles and communicates changes with the browser using Socket.IO. If your project allows Hot Module Replacement, webpack-dev-server can also update modules live in the browser without reloading the entire page which is very cool.
Usually when you’re developing with Django, the static files will be served by the development server and you’ll have something like this in your templates:
However, when you’re using webpack-dev-server you’ll have to serve your JS bundle from http://localhost:8080
(default host and port of webpack-dev-server) like this:
This works fairly OK if you have this setting exposed in your templates. The downside is that you manually have to change this setting each time you want to enable or disable webpack-dev-server during development, aside from starting webpack-dev-server.
To make life a little bit easier I’ve created a template tag that will serve the JS bundle from its normal location by default and automatically uses the webpack-dev-server version if that’s available:
Then, add your webpack bundle to your templates like this:
It adds a neglible performance cost of 1 local HTTP request during development, but I definitely think it’s worth it have your site automatically use the webpack-dev-server bundle when it’s available instead of manual switching. Another benefit is that you don’t see broken pages when you forget to start webpack-dev-server because the regular bundle will always be served.