Pranshu's Blog

Integrating TailwindCSS with React in 3 simple steps!

Integrating TailwindCSS with React in 3 simple steps!

Subscribe to my newsletter and never miss my upcoming articles

In this article I'll demonstrate how you can integrate TailwindCSS in React and also, how to purge unused CSS at the end. Let's begin!

Step 1: Adding TailwindCSS to your project

cd into your project directory and use the following command to install TailwindCSS: $ npm install tailwindcss

Step 2: Adding a build script

Open your package.json and add the following line in scripts:

"build:style": "tailwindcss build src/tailwind.css -o src/tailwind.output.css",

and, modify the start script to this:

"start": "npm run build:style && react-scripts start",

Your final scripts should look like the following:

"scripts": {
    "build:style": "tailwindcss build src/tailwind.css -o src/tailwind.output.css",
    "start": "npm run build:style && react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },

Now, create a new file called tailwind.css in your src directory and add the following lines:

@tailwind base;
@tailwind components;
@tailwind utilities;

Finally import tailwind.output.css in your index.js file:

// index.js
import './tailwind.output.css';

Step 3: Purging unused CSS

To purge the unused css and consequently reducing the total size, we will need to create a new file in the root directory of our project named tailwind.config.js and add the following lines of code in it:

module.exports = {
  purge: [
    'src/**/*.js',
    'src/**/*.jsx',
    'src/**/*.ts',
    'src/**/*.tsx',
    'public/**/*.html',
  ],
  theme: {
    extend: {},
  },
  variants: {},
  plugins: [],
}

Note: You'll also need to have the environment variable NODE_ENV set to production in order for purging to work.

And that's how you can add TailwindCSS to your React project in just 3 simple sreps!


If you made it so far, kudos to you! Be sure to leave your tips and suggestions down below in the comments!

 
Share this