How to install and setup TailwindCSS in a React+Vite project in 2023

How to install and setup TailwindCSS in a React+Vite project in 2023

Vite is a really, really fantastic toolchain for building front-ends. It's fast, has a great DX, and builds to a very small production size.

Another thing Vite does well is that it builds files needed in development on the fly without much setup and in this article, I'll show you how to easily set up TailwindCSS for fast styling changes.

Let's dive in

The setup

In your Vite-powered (npm?) React project, install the dependencies we'll be using

npm i --save-dev tailwindcss postcss autoprefixer

Tailwind

Next, run this command to initialize TailwindCSS for your project. It creates a file in your root directory called tailwind.config.cjs

npx tailwindcss init

Now, open the generated file, add a path to your files in the content array and save it. Here's what it should look like

/** @type {import('tailwindcss').Config} */
module.exports = {
    content: ['index.html', './src/**/*.{js,jsx,ts,tsx}'],
    theme: {
        extend: {},
    },
    plugins: [],
};

This adds our index.html file and every component in ./src, whether it's JS or TS.

PostCSS

Now create a file named postcss.config.cjs at the root of your project and paste this code inside

module.exports = {
    plugins: {
        tailwindcss: {},
        autoprefixer: {},
    },
};

That's all the setup we need.

Styling your components

Before you can start styling your components with TailwindCSS, you need to include it in your global CSS file (It's usually index.css) like so:

@tailwind base;
@tailwind components;
@tailwind utilities;

This informs Vite to build out the basic styles we need and reset the entire DOM's default styling.

Now we can start styling, open up any component file, add a tailwind class to it and save

You should see your styling changes reflect instantly in your browser

Bonus

For faster styling and a better DX, install the Tailwind CSS IntelliSense extension to get features like autocomplete, syntax highlighting, and linting.

Conclusion

In this article, I believe you've learnt how to set up TailwindCSS in your Vite project and style your components using it.

Thanks for reading, and I hope this article helps you. If you have any questions, you can drop a comment below and I'll reply.

Also, you can connect with me online via any of these platforms

Have a nice day.