DEV Community

Cover image for Integrating TailwindCSS with React in 3 simple steps!
Pranshu Jha
Pranshu Jha

Posted on • Updated on

Integrating TailwindCSS with React in 3 simple steps!

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",
Enter fullscreen mode Exit fullscreen mode

and, modify the start script to this:

"start": "npm run build:style && react-scripts start",
Enter fullscreen mode Exit fullscreen mode

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"
  },
Enter fullscreen mode Exit fullscreen mode

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

@tailwind base;
@tailwind components;
@tailwind utilities;
Enter fullscreen mode Exit fullscreen mode

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

// index.js
import './tailwind.output.css';
Enter fullscreen mode Exit fullscreen mode

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: [],
}
Enter fullscreen mode Exit fullscreen mode

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!

Top comments (0)