DEV Community

Cover image for How to add taillwindcss to an existing React project
Raphael MANSUY
Raphael MANSUY

Posted on

How to add taillwindcss to an existing React project

How to add taillwindcss to an existing React project

Go to directory of your React project and use yarn or npm to add taillwindcss postcss-cli autoprefixer

Using yarn

yarn add tailwindcss postcss-cli autoprefixer -D
Enter fullscreen mode Exit fullscreen mode

Then type this command in the terminal to create the default configuration

npx tailwind init tailwind.js --full
Enter fullscreen mode Exit fullscreen mode

A taillwind.js file is created in the current directory

Tailwind CSS is a highly customizable, low-level CSS framework that gives you all the building blocks you need to build bespoke designs without any annoying opinionated styles you have to fight to override

Create a postcss.config.js file

touch postcss.config.js
Enter fullscreen mode Exit fullscreen mode
const tailwindcss = require('tailwindcss');
module.exports = {
    plugins: [
        tailwindcss('./tailwind.js'),
        require('autoprefixer')
    ],
};
Enter fullscreen mode Exit fullscreen mode

PostCSS is a tool for transforming styles with JS plugins. These plugins can lint your CSS, support variables and mixins, transpile future CSS syntax, inline images, and more.

Create an assets directory in the src folder

mkdir ./src/assets
Enter fullscreen mode Exit fullscreen mode

Create a file called taillwind.css in ./src/assets

touch ./src/assets/tailwind.css
Enter fullscreen mode Exit fullscreen mode

Type in tailwind.css:

@import "tailwindcss/base";

@import "tailwindcss/components";

@import "tailwindcss/utilities";
Enter fullscreen mode Exit fullscreen mode

Modify the package.json file as follows:

"scripts": {
    "start": "yarn watch:css && react-scripts start",
    "build": "yarn build:css && react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "build:css": "postcss src/assets/tailwind.css -o src/assets/main.css",
    "watch:css": "postcss src/assets/tailwind.css -o src/assets/main.css"
  },
Enter fullscreen mode Exit fullscreen mode

A file called main.css will be generated each time we start the application

Then import the file ./src/assets/main.css in the App.js file (or the root file of the application)

import React from "react";
import ReactDOM from "react-dom";
import './assets/main.css';
import App from "./App";
ReactDOM.render(<App />, document.getElementById("root"));
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
mrpaulishaili profile image
Paul C. Ishaili

Beautifully written!

Collapse
 
iamsourabhh profile image
Sourabh Parmar

I wish it could be more simpler.