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.


npm i -D webpack webpack-cli webpack-dev-server

In your Webpack config add the following:


devServer: {
	contentBase: 'path/to/static',
	host: 'localhost',
	port: 8000,
	writeToDisk: true, // optional
	hot: true,
	index: '', // to proxy root
	proxy: { // proxy everything
		context: () => true,
		target: 'http://localhost', // address of Django server
	},
	// reload for our django files
	before(app, server) {
		const chokidar = require('chokidar') // this is dependencies used by webpack
		chokidar.watch('path/to/django/files').on('all', function(event, path) {
			server.sockWrite(server.sockets, 'content-changed');
		})
	},
}

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:


webpack-dev-server --config ./webpack.config.js --mode development

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.

Keywords: django, webpack