Setting Up Vite React.js with Tailwind CSS

Published on 24 June 2024

Learn how to set up a new React project using Vite and Tailwind CSS. This guide provides step-by-step instructions to help you configure a fast and efficient development environment for building modern web applications.

Introduction

In this tutorial, we will walk through the steps to set up a new React project using Vite as the build tool and Tailwind CSS for styling. Vite is a fast build tool and development server that significantly improves the development experience for modern web applications, while Tailwind CSS is a utility-first CSS framework that makes it easy to build responsive, custom user interfaces.

Prerequisites

  • Node.js installed on your machine
  • A code editor like VSCode

Step 1: Create a New Vite Project

First, we need to create a new Vite project. Open your terminal and run the following command:

npm create vite@latest

You will be prompted to name your project and select a framework. For this tutorial, choose React.

✔ Project name: vite-react-tailwind
✔ Select a framework: » React
✔ Select a variant: » JavaScript

Navigate to the project directory:

cd vite-react-tailwind

Install the project dependencies:

npm install

Step 2: Install Tailwind CSS

Next, we need to install Tailwind CSS and its peer dependencies:

npm install -D tailwindcss postcss autoprefixer

Initialize Tailwind CSS by creating the configuration files:

npx tailwindcss init -p

This will create two files: tailwind.config.js and postcss.config.js.

Step 3: Configure Tailwind CSS

Open the tailwind.config.js file and update the content array to include all the paths to your template files:

// tailwind.config.js
module.exports = {
  content: [
    "./index.html",
    "./src/**/*.{js,jsx,ts,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}

Step 4: Add Tailwind CSS to Your Project

Next, you need to add the Tailwind directives to your CSS. Create a new CSS file (e.g., src/index.css) and add the following lines:

/* src/index.css */
@tailwind base;
@tailwind components;
@tailwind utilities;

Import this CSS file in your main.js or main.jsx file:

// src/main.jsx
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
import './index.css'

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
)

Step 5: Start the Development Server

Now, you can start the development server to see your Vite and Tailwind CSS setup in action:

npm run dev

Open your browser and navigate to http://localhost:5173 to see the default Vite project styled with Tailwind CSS.

Conclusion

By following these steps, you've successfully set up a React project using Vite as the build tool and Tailwind CSS for styling. This setup provides a fast and efficient development experience, allowing you to build modern, responsive web applications with ease.