Let's say your working on a custom boilerplate or you have an older project that needs a migration and you want to use TailwindCSS.
You can very easily add TailwindCSS to any project thanks to the npx
command.
npx
is a script that lets you run other npm
scripts without having to install specific packages or fiddle with configurations.
To get started, we need to first install tailwindcss
and its peer dependency, autoprefixer
, into your project (make sure your project is using npm/yarn/pnpm).
npm i tailwindcss autoprefixer
For those unfamiliar, autoprefixer
is a PostCSS script that just adds some browser-specific properties and fixes to your CSS to ensure it behaves the same across different browsers (Chromium, Safari, Firefox, etc.).
With those two packages installed, we can then run the initializer script for TailwindCSS using npx
:
npx tailwindcss init -p
This command will generate the following files:
tailwind.config.js
postcss.config.js
Depending on your use case, you may not need a postcss.config.js
file. If you're using a bundler like Webpack, Vite, etc. then you will need this file.
Head into tailwind.config.js
and update the content
key so that it includes all of your source files. Make sure the file extension(s) are correct!
Here's an example tailwind.config.js
file for a React project:
/** @type {import('tailwindcss').Config} */
module.exports = {
content: ["./src/**/*.{jsx,tsx}"],
theme: {
extend: {},
},
plugins: [],
}
Last step, we need to update our global CSS file to include TailwindCSS's preflight directives.
At the very top of that file, add the following three directives:
/* globals.css */
@tailwind base;
@tailwind components;
@tailwind utilities;
/*... Rest of CSS */
That's it! You should now be able to run npm run dev
(or whatever your development script is) be able to start using TailwindCSS.