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.
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>
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.
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.