CN
Piotr Jura·
April 25, 2024

How to add Tailwind CSS to a Vite based Vue project?

I'd assume you already have your Vue project created using Vite. If you don't here's how to do that.

How to install Tailwind CSS in a Vue Vite project?

Start by running following in the Terminal.

Terminal
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p

This would create an a tailwind.config.js file at the root directory of your project, that looks like this:

tailwind.config.js
/** @type {import('tailwindcss').Config} */
export default {
  content: [],
  theme: {
    extend: {},
  },
  plugins: [],
}

Change the file to:

/** @type {import('tailwindcss').Config} */
export default {
  // Make changes below
  content: [
    "./index.html",
    "./src/**/*.{vue,js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}

The change tells Tailwind CSS where to look for the CSS utility classes. Keep in mind, the Tailwind purges all non used utlity classes from the final bundle, so you need to point to all files where Tailwind classes are used.

The above will look into index.html and then all *.vue files (and other extensions above) inside the src directory, including subdirectories.

How to add Tailwind CSS to a Vue project?

Change the main.css file, or however your main CSS file name is, adding the following Tailwind CSS directives:

src/assets/main.css
@tailwind base;
@tailwind components;
@tailwind utilities;

Visual Studio Code might highlight these directives with a warning: "Unknown at rule @tailwindcss(unknownAtRules)". To remove this and other Tailwind CSS related warnings (these are not errors, VS Code thinks you are using directives that don't exist in CSS), you can configure VSCode (using per project config file):

.vscode/settings.json
{
  "css.lint.unknownAtRules": "ignore"
}

How to make sure the Tailwind CSS is installed and set up correctly with Vue/Vite project?

To check if everything was set up correclty, run npm run dev command in the terminal, to start a local development server. Use any of the Tailwind CSS classes on the page, and if it works as intented it means the setup is done.

Also make sure to run npm run build to test if all the Tailwind classes that you are using in the project are correctly included with the production bundle.