How to use TailwindCSS with Django?

David D. picture David D. · Aug 13, 2020 · Viewed 7.3k times · Source

How to use all features of TailwindCSS in a Django project (not only the CDN), including a clean workflow with auto-reloading, and purgeCSS step to be production-ready?

When googling, I found a python package named django-tailwind but it did not really helped me in the process.

Answer

David D. picture David D. · Aug 13, 2020

TL;DR

  1. Install TailwindCSS within your Django project, like any JS project with npm
  2. Use a live-reload server package with Django
  3. Add purgeCSS config before deploying

More detailed explanation

1 - The TailwindCSS build process

Create a new directory within your Django project, in which you'll install tailwindCSS like in any vanilla JS project setup:

cd your-django-folder; mkdir jstoolchain; cd jstoolchain
npm install tailwindcss postcss-cli autoprefixer
npx tailwind init
touch postcss.config.js

In this postcss.config.js file, add:

module.exports = {
    plugins: [
        require('tailwindcss'),
        require('autoprefixer')
    ]
}
mkdir css; touch css/tailwind.css

In this tailwind.css file, add at least this:

@tailwind base;
@tailwind components;
@tailwind utilities;

Now, add a script in your jstoolchain/packages.json file to create the build process and specify the output file, such as:

{
  "scripts": {
    "build": "postcss css/tailwind.css -o ../your-django-folder/your-path-to-static/css/tailwind-output.css"
  }
}

Now, run;

npm run-script build

This should run without error, and tailwind-output.css should be now filled with thousands of lines. Now you can actually use tailwindCSS classes, by including the outputted css file into a Django template file along with Django's call to load the static files:

{% load static %}

<head>
  <link rel="stylesheet" href="{% static "css/tailwind-output.css" %}">
</head>

2 - Handling auto-reload locally

What's missing now to ease development, is to auto-reload the django development server when an HTML file is changed and saved. For this, I installed django-livereload-server.

Just follow setup instructions, this will work as expected out of the box, without any special configuration.

3 - The purgeCSS process

When you're ready to deploy, to ensure the CSS output file is not bloated with useless classes, go to jstoolchain/tailwind.config.js file, and add:

  purge: {
    enabled: true,
    content: ['../your-django-folder/path-to-your-templates/**/*.html'],
  },

Now, running build script should produce a much smaller CSS output, production-ready file.


Ideas to improve the workflow

  • The build script could be run automatically when the input tailwind files (css, js) are edited
  • PurgeCSS could be run automatically when required, rather than adding it or removing it manually.
  • Any other idea?