DEV Community

Cover image for Setup TailwindCSS with React.js application and remove the unused styles using PurgeCSS
Theena Dayalan
Theena Dayalan

Posted on

Setup TailwindCSS with React.js application and remove the unused styles using PurgeCSS

Originally post at https://www.theenadayalan.me/blog/setup-tailwindcss-in-react-application.

TailwindCSS is a utility-first, 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.

Every Web developer in the world is using Bootstrap as their first front-end component library. Because it is simple and easy to build the CSS components with a few bootstrap classes. They will be in flying colors because they have built Dropdown, Navbar, Tooltip, etc using a few CSS classes.

The real problem comes once they start introducing custom design(styles). They will have to override many Bootstrap CSS classes to make up their custom designs. Here TailwindCSS has the advantage over bootstrap, it has all the utility classes to build our custom design. It is also having component classes for starter projects.

Bootstrap is also having utility classes, but they are very few. and non-customizable. TailwindCSS is a fully customizable and low-level CSS framework.

In this post, We are going to explore how to setup TailwindCSS with React.js application using Webpack and PostCSS.

Prerequisites

Before adding TailwindCSS into your project, you must not be using create-react-app since we are gonna do manual Webpack configuration which create-react-app restricts. You should be built the project from scratch.

If you are new to React.js, Please follow my previous post on setting up the React.js application from scratch.

Installation

Follow the below steps to install the required packages to add TailwindCSS to your React application.

Setting up TailwindCSS

First, we will learn how to add TailwindCSS to the project using Webpack and PostCSS.

Install TailwindCSS and PostCSS.

  yarn add tailwindcss
Enter fullscreen mode Exit fullscreen mode

tailwindcss - TailwindCSS library

Import the TailwindCSS library styles into our application style.

src/style.css

  @tailwind base;
  @tailwind components;
  @tailwind utilities;
Enter fullscreen mode Exit fullscreen mode
  yarn add -D postcss postcss-loader css-loader mini-css-extract-plugin
Enter fullscreen mode Exit fullscreen mode

postcss - CSS transformation tool.

css-loader - Interprets @import and url() like import/require().

mini-css-extract-plugin - Extracts CSS into separate files, say style.css.

postcss-loader - PostCSS loader for webpack.

Let's add the webpack configurations.

webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
  entry: path.resolve(__dirname, 'src/index'),
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  module: {
    rules: [{
      test: /\.js$/,
      include: path.resolve(__dirname, 'src'),
      use: ['babel-loader']
    }, {
      test: /\.css$/,
      use: [
        {
          loader: MiniCssExtractPlugin.loader
        },
        'css-loader',
        'postcss-loader'       
      ]
    }]
  },
  devServer: {
    contentBase:  path.resolve(__dirname, 'dist'),
    port: 9000
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: "styles.css"
    }),
    new HtmlWebpackPlugin({
      template: "src/index.html" //source html
    })
  ]
};
Enter fullscreen mode Exit fullscreen mode

let's add the PostCSS configurations.

postcss.config.js

module.exports = {
  plugins: [
    require('tailwindcss')
  ]
}
Enter fullscreen mode Exit fullscreen mode

That's all! We are done. It's testing time. Let's add some tailwindcss styles to our project.

src/index.js

import React from 'react';
import { render } from 'react-dom';
import './style.css';

const rootElement = document.getElementById('react-app');

render(<div className="text-pink-600 text-center text-5xl"> Hello World! </div>, rootElement);
Enter fullscreen mode Exit fullscreen mode

Phewww!! Let's see what we have done.

Output Before Adding PurgeCSS

See! Very simple right?

Here comes the real villain, Let's check the Bundle Size

Bundle Size Before Adding PurgeCSS

The size of the CSS file is 549KB. We used only a few classes but the bundle includes all the CSS classes that we don't actually use. (maybe we will never use it). Here comes the PurgeCSS as a lifesaver.

Setup PurgeCSS

PurgeCSS is a tool to remove unused CSS. We need to configure it with our PostCSS tool to get the benefit of PurgeCSS.

  yarn add -D @fullhuman/postcss-purgecss
Enter fullscreen mode Exit fullscreen mode

@fullhuman/postcss-purgecss - PostCSS plugin for PurgeCSS

Configure postcss.config.js to support PurgeCSS.

postcss.config.js

const purgeCSS = require('@fullhuman/postcss-purgecss');

module.exports = {
  plugins: [
    require('tailwindcss'),
    purgeCSS({
      content: [
        './src/**/*.js',
      ],
      css: ['./src/**/*.css']
    })
  ]
}
Enter fullscreen mode Exit fullscreen mode

That's all for the configurations. Now check the build size.

Bundle Size After Adding PurgeCSS

From 549KB to 8.34KB.

98.4% of CSS got reduced by Adding PurgeCSS 😃.

Fully completed code can be found here.

I hope this post is useful in some way for others. ❤️

Top comments (2)

Collapse
 
chinuxparibus profile image
Jhony Alberto Grillet Medina

This is exactly what I was looking for because on many tutorials I had watched, they don't explain how to use webpack to minimize and purge the CSS.
My bundle was 5MB until this point.
Thank you, Theena. You rock!
You read it from an avocado🥑

Collapse
 
castillomike profile image
Miguel Ángel

Hello is there a way to purge tailwind styles if they are shared from react context?