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

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

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
  • Paste this in tailwind.config.js:
module.exports = {
    mode: "jit",
    purge: ["./public/**/*.html", "./src/**/*.{js,jsx,ts,tsx}"],
    theme: {},
};
  • Paste this in postcss.config.js:
module.exports = {
  plugins: [
    require("postcss-import"),
    require("tailwindcss"),
    require("autoprefixer"),
  ],
};

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
  • Add following code inside tailwind.pcss
@import "tailwindcss/base.css";
@import "tailwindcss/components.css";
@import "tailwindcss/utilities.css";

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"
},

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;

Now open two terminals and run these commands separately

yarn watch:css

and

yarn start

The output should be:

Congrats! You have successfully installed and used tailwindcss 🚀🚀

28