How to use TailwindCSS with Django?

后端 未结 3 1420
独厮守ぢ
独厮守ぢ 2021-01-30 15:05

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?

W

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-30 15:57

    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 %}
    
    
      
    
    

    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?

提交回复
热议问题