First, install all the necessary dependencies:
npm install tailwindcss autoprefixer postcss postcss-cli
Tailwind is by itself a plugin for PostCSS, and PostCSS is a tool for transforming CSS. To create a PostCSS configuration file, run :
npx tailwindcss init -p
This will create both a postcss.config.js
and tailwind.config.js
file. The PostCSS config file will be set up to use the autoprefixer
plugin too (which we installed at the beginning), which will add browser-specific prefixes to your CSS so it works in all browsers.
In your tailwind.config.js
file, set the purge
option to point to your React components. This will allow Tailwind to remove the CSS classes you didnāt use to make the final CSS file smaller in production. If your React components are in the src/
directory, for example:
// excerpt from tailwind.config.js
purge: ["./src/**/*.js"];
Next, fill out your CSS file. Some React Static templates have the CSS file at src/app.css
, so weāll replace the contents of that file with this:
@tailwind base;
@tailwind components;
@tailwind utilities;
When this file goes through PostCSS, those three @tailwind
directives will be replaced with the full Tailwind CSS framework.
Weāre nearing the end here! We need to add commands for building this CSS file, both in development and production. Weāll use the PostCSS CLI (which we installed earlier) for that, and modify the following two commands in your package.json
:
// excerpt from package.json
"start": "NODE_ENV=development postcss src/app.css > dist.css && react-static start",
"build": "NODE_ENV=production postcss src/app.css > dist.css && react-static build"
Itās important to define NODE_ENV
, because that determines whether Tailwind will āpurgeā all your unused classes.
Those commands output the built version of src/app.css
to a file called dist.css
. Youāll see it in your projectās folder after running either of those commands.
We donāt really want that file to be uploaded to Git, so weāll add it to our .gitignore
file so it doesnāt get committed. This is optional, and only if youāre using Git for version control.
# excerpt from .gitignore file
dist.css
Lastly! We want to actually use that outputted dist.css
file. In your src/App.js
component, thereās a line that imports the ./app.css
file. However, thatās the un-built CSS file ā the fully processed and built one lives at dist.css
. So switch that import line in src/App.js
to this:
import "../dist.css";
And thatās it! Now you have Tailwind CSS working with a React Static website, both in development and production.