Adding TailwindCss to a Django Website

I hate CSS and I love CSS, but I mostly hate it.I mostly hate it because it take ups so much of my time and I find that it really knocks the wind out of my productivity sails. I take my hat off to people who can can do it, I just recognise my limitations and need to find a new way. That way is I hope tailwindcss

My website was in need of a massive refresher. I wanted to start blogging more but in truth was a bit ashamed of the look of the site. Here are some images of what it looked like before I revamped it with tailwindcss.

OldSIte Old2

It's a sad website really and I am hopeful that you are reading this on something looking a little more professional. Ok lets start.

Prerequisites

  1. working django project
  2. npm
  3. webpack

Step 0 : Read tailwindcss documentation

Summarising what I have read on tailwindcss.com there are a few options of getting going with tailwindcss. It says For most real-world projects, we recommend installing Tailwind as a PostCSS plugin so I am not going to bother with the other methods as I'm a fan of following recommendations. So the following needs to happen:

Step 1 : Install Tailwind via npm

npm install -D tailwindcss@latest postcss@latest autoprefixer@latest

Step 2 : Create postcss config

touch postcss.config.js
// postcss.config.js
module.exports = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  }
}

Step 3 : Create Tailwind config

npx tailwindcss init

This creates the following:

//tailwind.config.js
module.exports = {
  purge: [],
  darkMode: false, // or 'media' or 'class'
  theme: {
    extend: {},
  },
  variants: {
    extend: {},
  },
  plugins: [],
}

Now I need to go find my css in my base.html

<!--base.html--> 
{# Global stylesheets #}
<link rel="stylesheet" type="text/css" href="{% static 'css/main.css' %}">

Step 4 : Add Tailwind to your main.css

Here is what mine looks like:

@tailwind base;

@layer base {
  h1 {
    @apply text-2xl;
  }
  h2 {
    @apply text-xl;
  }
  h3 {
    @apply text-lg;
  }
  ol,
  ul {
    @apply list-disc;
  }
}

@tailwind components;
@tailwind utilities;


.token.operator {
  background: none !important;
}

Step 5: Tweak your Tailwind Config

/* tailwind.config.js */

module.exports = {
  purge: { content: ['./**/templates/**/*.html','../envs/**/*.html'],},
  darkMode: false, // or 'media' or 'class'
  theme: {
    extend: {
      colors: {
        yellow: "#EAC543",
        orange: "#F59E0B"
      },
    },
  },
  variants: {
    extend: {},
  },
  plugins: [require("@tailwindcss/forms")],
};

In my one I have added some custom colours and I have added a paths to the purge section which will reduce the size of my css files to only classes used by my templates or third party templates which will be a 3mb saving :) For this you need to set the environment variable NODE_ENV=production

Step 6: Tweak your Webpack Config

/* webpack.config.js */

var path = require("path");
var webpack = require('webpack');
var BundleTracker = require('webpack-bundle-tracker');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = {
  context: __dirname,
  mode: 'development',
  entry: {
    index: './chriswedgwood/static/js/index.js',
    main:'./cwedgtail/static/css/main.css',
    
  }

  ,
  output: {
    path: path.resolve('./chriswedgwood/static/bundles/'),
    filename: "[name]-[hash].js",
    publicPath: ''
  },

  plugins: [
    new BundleTracker({
      filename: './webpack-stats.json'
    }),
    new MiniCssExtractPlugin({
      // Options similar to the same options in webpackOptions.output
      // both options are optional
      filename: '[name]-[hash].css',
      }),
  ],
  module: {
    rules: [{
      test: /\.js$/,
      
      exclude: /node_modules/,
      loader:   'babel-loader',
      
      options: {
        presets: ['@babel/preset-env',
          '@babel/react', {
            'plugins': ['@babel/plugin-proposal-class-properties','@babel/transform-runtime']
          },
          
        ]
      }
    },
    {
      test: /\.(png|jpg|gif)$/,
      use: [
        {
          loader: 'file-loader',
          options: {
            name: '[name].[ext]',
            outputPath: 'images/',
            publicPath: ''

          }
        }
      ]
    },
    {
      test: /\.css$/i,
      use: [MiniCssExtractPlugin.loader, 'css-loader','postcss-loader'],
    },]
  },
  resolve: {
    extensions: ['*', '.js', '.jsx']
  },



};

Thats my whole file which can be helpful to see. The important lines are

main:'./cwedgtail/static/css/main.css',

use: [MiniCssExtractPlugin.loader, 'css-loader','postcss-loader'],

This is just saying create a bundle called main and use we need the postcss-loader to convert the tailwind stuff we added to main.css into actuall css

Step 7: Add Django webpack loader

pip install django-webpack-loader==0.7.0

This will enable us to load our webpack bundle into our templates using the following:

<!-- base.html -->
{% load render_bundle from webpack_loader %}

<head>

 {% render_bundle 'main' %}

</head>

Step 8: Build bundle with npm

npm run build

That should do it!