Harnessing the power of Webpack for Django development
Webpack has become the de facto JS build tool. It is used in almost every front end project; whether it's a SPA written in React or a HTML site styled with SCSS. Because of this, backend developers who work with Django or Laravel cannot escape Webpack. If you can't beat them, join them.
How can Webpack help?
With Webpack we can automatically reload the page when our Django code changes. Similarly, we can also take advantage of Webpack Hot Module Replacement to hot reload our CSS and JS files. We can achieve that by using the Webpack Dev Server as a proxy for our Django server. The Webpack dev server will handle all the frontend request and pass the rest to Django.
The Setup
Let's install all the dependencies for this to work.
1 | |
In your Webpack config add the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |
Set contentBase to point to your Django static directory. This is where Webpack will serve all the static content and client code.
The proxy option will send all request it cannot handle to your Django server, while serving the CSS and JS files themselves. This is how we achieve HMR.
In the before config, we will watch any Django files that we want to trigger a full page reload. A good candidate would be the template files.
Run the following command to start the dev server:
1 | |
You might also want to add a command to your npm scripts for easy access.
New Levels of Productivity
Now you can edit your JS, CSS, HTML, and Python files and have them reload automatically. We achieved that with only one Webpack config and no change to our work flow.