2020 / 04 / 09
How to add Tailwind CSS to Vue.js

My new favorite utility-first CSS framework!

vue.js
tailwindcss
purgecss

Basic setup

This guide builds on Quickstart guide for a new Vue.js project.

We are going to setup Tailwind CSS + PurgeCSS to get a very lean CSS system that’ll only include what we actually use from Tailwind.

Install dependencies

yarn add tailwindcss
yarn add --dev @fullhuman/postcss-purgecss

Generate Tailwind CSS config file

Create a ready-to-be-extended tailwind.config.js file:

npx tailwind init # --full

If you want a full config file, you can remove the # and pass the --full flag to the command above.

Import Tailwind classes

Create a src/assets/styles/tailwindcss.sass file:

/*! purgecss start ignore */
@import "tailwindcss/base"
@import "tailwindcss/components"
/*! purgecss end ignore */

@import "tailwindcss/utilities"

Here we instruct PurgeCSS to not purge the classes contained inside tailwindcss/base and tailwindcss/components.

Import the Sass file on your src/main.js file:

--- a/src/main.js
+++ b/src/main.js
@@ -9,6 +9,8 @@ import './plugins/vue2-filters'
 import './plugins/vuelidate'
 import { version } from '../package.json'
 
+import '@/assets/styles/tailwindcss.sass'
+
 
 /* eslint-disable no-console */
 console.log(`App v${version}`)

Set up PurgeCSS

Finally, create a postcss.config.js file at your project’s root, with this content:

const purgecss = require('@fullhuman/postcss-purgecss')({
  // Specify the paths to all of the template files in your project
  content: [
    './src/**/*.html',
    './src/**/*.vue',
    './src/**/*.jsx'
  ],

  // Include any special characters you're using in this regular expression
  defaultExtractor: content => content.match(/[\w-/:]+(?<!:)/g) || []
})


module.exports = {
  plugins: [
    require('tailwindcss'),
    require('autoprefixer'),
    ...process.env.NODE_ENV === 'production'
      ? [purgecss]
      : []
  ]
}

Class whitelisting

If PurgeCSS is cleaning a family of classes that you need, you prevent that by whitelisting them.

Let’s say you are using Leaflet to display map information on your app.

You can whitelist all classes that contain the string leaflet by adding the whitelistPatterns attribute to the PurgeCSS config object like this:

--- a/postcss.config.js
+++ b/postcss.config.js
@@ -8,7 +8,10 @@ const purgecss = require('@fullhuman/postcss-purgecss')({
   ],
 
   // Include any special characters you're using in this regular expression
-  defaultExtractor: content => content.match(/[\w-/:]+(?<!:)/g) || []
+  defaultExtractor: content => content.match(/[\w-/:]+(?<!:)/g) || [],
+
+  // Whitelist classes
+  whitelistPatterns: [/leaflet/]
 })