How to setup Laravel 7 with tailwind and purgeCss

How to use TailWindCSS with Laravel Framework and PurgeCSS

Tailwind CSS is utility-first CSS framework and it is the best framework for full stack developers because it is highly customizable, low-level CSS framework that gives you all of the building blocks you need to build bespoke designs without any annoying opinionated styles you have to fight to override.

How to setup Laravel 7 with tailwind and purgeCss

In this tutorial I am going to guide you on how you can install tailwind framework inside your Laravel project with purgeCSS

I use tailwind css for pretty much all of my projects at work and personal side projects.It enables me to get up and running quickly, creating custom styling for DOM elements in a sleek and professional way.

Setup Tailwind for Laravel

I assume that you already have created a Laravel application if not you can create with laravel install or composer or read Laravel Docs about installing laravel.

Once your project is created, you can run php artisan serve from the project folder to start a local server and open localhost:8000 in your browser to see the default Laravel welcome page.

Now, Follow following step to setup tailwind in Laravel.

  1. Install Tailwind

To install tailwindcss, open you terminal and navigate into your application root directory and execute following command, if you are windows use then open command prompt:


            npm install tailwindcss
        
  1. Add Tailwind to your CSS

Now the tailwindcss has been added to our node_modules and we are ready to use it in our project.

Go ahead and add following lines to /resources/sass/app.scss file


            @tailwind base;
            @tailwind components;
            @tailwind utilities;
        
  1. Create your Tailwind config file (optional)

Now the next step is to generate tailwind config file into root of our Laravel application.Tailwind allows you to customize your fonts, colours and a lot of other things in this file so check the corresponding page of their official docs for more info.

This file is going to be used by laravel mix when we will build scss into css.

Execute following command to generate tailwind config file:


npx tailwindcss init

After running above command if you check into root of your project you will see new file created called tailwind.config.js, it should have following JS configuration written:


            module.exports = {
                theme: {},
                variants: {},
                plugins: [],
            }              
        
  1. Add TailWind into Laravel Mix Build Process

Now we have to add tailwind into Laravel mix build process basically will have to tell laravel mix to compile tailwind sass using the tailwind configuration file.

Laravel mix configuration can be located at webpack.mix.js, so go ahead and open webpack.mix.js file: You should see following default configuration:


            const mix = require('laravel-mix');
            mix.js('resources/js/app.js', 'public/js')
                .sass('resources/sass/app.scss', 'public/css');
        

Replace it with following configuration:


            const mix = require('laravel-mix');
            const tailwindcss = require('tailwindcss');

            mix.js('resources/js/app.js', 'public/js')
                .sass('resources/sass/app.scss', 'public/css')
                .options({
                    processCssUrls: false,
                    postCss: [tailwindcss('./tailwind.config.js')],
                });
        

processCssUrls is disabled as this option does not work with `.sass` files read more here

  1. Examples of Using TailWind CSS

Now we can use tailwind utility class into our project. I am going to demonstrate example uses of tailwind css on welcome.blade.php

First Let’s import app.css file into welcome.blade.php file by adding following line just before closing head tag (</head>):


            <link href="{{ asset('css/app.css') }}" rel="stylesheet">
        

Now, add class bg-teal-200 text-red-600 to body tag as follow:


            <body class="bg-teal-200 text-red-600">
        

But now tailwind supports integratd purgeCss option. So you don’t need any third party packages. Simply add purge property to tailwind config file as follow:

  module.exports = {
  purge: {
    // enabled: true,
    content: [
      "app/**/*.php",
      "resources/**/*.html",
      "resources/**/*.js",
      "resources/**/*.jsx",
      "resources/**/*.ts",
      "resources/**/*.tsx",
      "resources/**/*.php",
      "resources/**/*.vue",
      "resources/**/*.twig",
    ],
    options: {
      // defaultExtractor: (content) => content.match(/[w-/.:]+(?<!:)/g) || [],
      whitelistPatterns: [/-active$/, /-enter$/, /-leave-to$/, /show$/],
    }
  },
  theme: {
    extend: {},
  },
  variants: {},
  plugins: [],
}

One of the inconveniences of Tailwind CSS is its size. As it has so many classes the size of the whole library is very big but we can use purgeCSS to remove all classes we are not using in our project. Similar to what we did to install Tailwind, we need to install a Laravel Mix plugin, in this case with the command npm i laravel-mix-purgecss --save-dev. Once installed, we need to add a few lines to our webpack.mix.js file:

Introducing Laravel Mix PurgeCss

Laravel-mix-purgecss is a npm package which is preset to scan all relevant files within the /Resources folder for css styling, and uses purgeCss to delete all unused css styling from the final compiled .css file. You can install configure it as follow:

Steps to Install and setup purgeCSS

Before you get started, make sure you’re using laravel-mix version 5.0.0 or higher.

  1. Install Laravel PurgeCSS package

You can install the package with npm:

        
            npm install laravel-mix-purgecss --save-dev
         
  1. Configure purgeCSS for Mix

Now, Install the extension by requiring the module in your Mix configuration after tailwindcss require statement in webpack.mix.js as follow:

        
            const mix = require('laravel-mix');
            const tailwindcss = require('tailwindcss');
            require('laravel-mix-purgecss');

         

PurgeCSS can be enabled by calling .purgeCss() in your Mix chain.So,Go to webpack.mix.js and add:

        
            mix.js('resources/js/app.js', 'public/js')
                .sass('resources/sass/app.scss', 'public/css')
                .options({
                    processCssUrls: false,
                    postCss: [tailwindcss('./tailwind.config.js')],
                })
                .purgeCss();
         

With this configuration, we’ll only run purgeCSS when we generate our production build with npm run prod. Go ahead and run it and compare the file sizes with the ones generated with npm run dev . In my case, the difference in the app.css file is ~1Kb in production and 1.23Mb in development. That’ll make a huge difference in the loading time of our web!

By default, PurgeCSS only works when building assets for production (npm run prod). You can override this behaviour by specifying the enabled option. read here

Thats all now your app is fully set to use power of Laravel, Laraveland purgeCss</>

Hope you find this useful. I’ve uploaded a scaffolded project to this public repo in GitHub so you can just clone it and start using it as the base for your next project. Just remember to follow the instructions in the Readme to install all dependencies!

How to setup Laravel 7 with tailwind and purgeCss

Oh hi there 👋
It’s nice to meet you.

Sign up to receive awesome content in your inbox.

We don’t spam! Read our privacy policy for more info.

Share your love
itxshakil
itxshakil

Hi, I'm Shakil Alam, a passionate web developer from Faridabad, India. I have experience in developing real-time web applications, complex front-end, and back-end management systems.

Articles: 25

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.