DEV Community

kiranojhanp
kiranojhanp

Posted on

Add tailwind (JIT) to a react app without ejecting or using craco

React and tailwind without ejecting

Hello guys,
Official tailwindcss docs uses a package called craco during installation of tailwindcss in react app.

I don't particulary like it because same can easily be achieved with just postcss. Here are the steps.

Step 1 - Create a react and add dependencies

# install react and navigate inside
npx create-react-app my-app
cd my-app

# install packages
yarn add autoprefixer postcss postcss-cli postcss-import tailwindcss

# replace yarn add with npm install if using npm
Enter fullscreen mode Exit fullscreen mode

Step 2 - Add configs

  • Create two files tailwind.config.js and postcss.config.js in root
├── src/
├── tailwind.config.js
├── postcss.config.js
└── package.json
Enter fullscreen mode Exit fullscreen mode
  • Paste this in tailwind.config.js:
module.exports = {
    mode: "jit",
    purge: ["./public/**/*.html", "./src/**/*.{js,jsx,ts,tsx}"],
    theme: {},
};

Enter fullscreen mode Exit fullscreen mode
  • Paste this in postcss.config.js:
module.exports = {
  plugins: [
    require("postcss-import"),
    require("tailwindcss"),
    require("autoprefixer"),
  ],
};

Enter fullscreen mode Exit fullscreen mode

Step 3 - Create styles

  • Create a folder styles inside src
  • Create tailwind.pcss and output.css inside it
src/
├── styles/
         ├── output.css
         └── tailwind.pcss
├── App.js
└── index.js
Enter fullscreen mode Exit fullscreen mode
  • Add following code inside tailwind.pcss
@import "tailwindcss/base.css";
@import "tailwindcss/components.css";
@import "tailwindcss/utilities.css";
Enter fullscreen mode Exit fullscreen mode

Step 4 - Modify package.json

Replace scripts with

"scripts": {
    "start": "react-scripts start",
    "build": "yarn build:css && react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "watch:css": "TAILWIND_MODE=watch postcss src/styles/tailwind.pcss -o src/styles/output.css --watch",
    "build:css": "postcss src/styles/tailwind.pcss -o src/styles/output.css --minify"
},
Enter fullscreen mode Exit fullscreen mode

Note: Just replace yarn with npm run if you are a npm user

Step 5 - Running

Replace App.js with:

import "./styles/output.css"
function App() {
 return (
   <div class="bg-green-100 border-green-600 border-b p-6 m-4 rounded text-2xl text-center">
     Hello World
   </div>
 );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Now open two terminals and run these commands separately

yarn watch:css
Enter fullscreen mode Exit fullscreen mode

and

yarn start
Enter fullscreen mode Exit fullscreen mode

The output should be:

Tailwindcss output image

Congrats! You have successfully installed and used tailwindcss 🚀🚀

Oldest comments (0)