Tailwind + Vue

I can't stress enough how happy I am after start using Tailwind CSS in my Vue projects. Now, I don't have to deal directly with CSS; Tailwind will handle that for me 😉.

This is a short tutorial on how to add Tailwind CSS to your Vue app created with the Vue CLI. Let's start:


1) Open your project and install Tailwind.

npm i --save-dev tailwindcss

2) Create a CSS file called tailwind.css in the following path src/assets/css/ and add the content below:

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

3) Now import the tailwind.css in main.js


import './assets/css/tailwind.css'

4) Create your Tailwind config file by running

npx tailwindcss init

This will create a minimal tailwind.config.js file at the root of your project.

5) Create a postcss.config.js file at the root of your app and add this:


const autoprefixer = require('autoprefixer')
const tailwindcss = require('tailwindcss')
module.exports = {
plugins: [    tailwindcss,    autoprefixer  ]
}

At this point, Tailwind is ready to be used, but if you try to compile the app you will get a warning because your CSS bundle size is too big, around 850 KiB. So let's use PurgeCSS to downsize it by removing the unused CSS.



6) Install PurgeCSS:

npm i --save-dev @fullhuman/postcss-purgecss

7) Set up PurgeCSS in our postcss.config.js file (only enabled  in production):

const autoprefixer = require('autoprefixer')
const tailwindcss = require('tailwindcss')
const postcssPurgecss = require('@fullhuman/postcss-purgecss')
const purgecss = postcssPurgecss({
  content: ['./public/**/*.html''./src/**/*.vue'],
  defaultExtractor: content => content.match(/[\w-/:]+(?<!:)/g) || [],
  // Whitelisted classes (E.g.: The router-link active class)  

whitelistPatterns: [
    /-(leave|enter|appear)(|-(to|from|active))$//^(?!(|.*?:)cursor-move).+-move$/, /^router-link(|-exact)-active$/  ]
})
module.exports = {
  plugins: [
    tailwindcss,
    autoprefixer,
    ...(process.env.NODE_ENV === 'production' ? [purgecss] : []),
  ]
}

8) Edit the tailwind.css file to only apply PurgeCSS on utility classes, and not to base styles or component classes:
/* purgecss start ignore */
@tailwind  base;
@tailwind  components;
/* purgecss end ignore */
@tailwind  utilities;

Done, now if we compile our app, we will get a smaller CSS bundle size, around 4 KiB.





Bonus
If you are using VS Code, install Tailwind CSS IntelliSense to get suggestions as you type + some features that will improve the Tailwind experience.

Popular posts from this blog

GitHub Pages + Vue CLI 3

Vue.js Google Sign-In button

Let's talk about Web Accessibility