Create a React + TypeScript + Tailwind project with Vite
To quickly bootstrap a new React project with TypeScript using Vite, you can use the following npm command:
shellnpm create vite@latest react-app -- --template react-ts
Or if you prefer yarn:
shellyarn create vite react-app --template react-ts
This will create a new directory called react-app with a basic project structure already set up for a React + TypeScript application.
Once the project is created, navigate into the directory:
shellcd react-app
Then install the dependencies:
shellnpm install
Finally, start up the dev server:
shellnpm run dev
Install and configure Tailwind
To install Tailwind CSS and its peer dependencies, run:
shellnpm install tailwindcss@latest postcss@latest autoprefixer@latest @headlessui/react @heroicons/react --save-dev
Next, you'll need to generate a Tailwind configuration file:
shellnpx tailwindcss init -p
Open the index.css file in your project's src directory and replace its content with the following:
index.css@tailwind base;
@tailwind components;
@tailwind utilities;
html {
@apply h-full;
}
body {
@apply h-full;
}
#root {
@apply h-full;
}
To import Tailwind in the project, open the main.tsx file and add the following line at the top of the file (if it's not already there)
htmlimport './index.css';
Removing Unnecessary CSS Imports
If you have any existing CSS imports in your .tsx files, you can now remove them. Tailwind CSS will handle all the styling for you, so you don't need to import individual CSS files anymore.
Configuring Tailwind CSS Content
To ensure that Tailwind CSS can purge unused styles and optimize your final CSS bundle, you need to specify the content files where Tailwind classes are used. Open the tailwind.config.js file in your project root and add the following configuration:
tailwind.config.js/** @type {import('tailwindcss').Config} */
export default {
content: [
"./index.html",
"./src/**/*.{js,ts,jsx,tsx}"
],
theme: {
extend: {},
},
plugins: [],
}
In the content array, you specify the paths to your HTML and JavaScript/TypeScript files where Tailwind classes are used. This configuration tells Tailwind CSS to scan the index.html file and all the files with .js, .ts, .jsx, or .tsx extensions in the src directory and its subdirectories.