28
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.
# 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
- Create two files
tailwind.config.js
andpostcss.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"),
],
};
- Create a folder
styles
insidesrc
- Create
tailwind.pcss
andoutput.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";
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
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;
yarn watch:css
and
yarn start
The output should be:
28