How to use Tailwind CSS with Nuxt

How to use Tailwind CSS with Nuxt

Tailwind CSS is a utility-first CSS framework that is easily modified to suit your intended style. It comes with an extensive range of classes for your HTML markup to create components such as cards, buttons, form inputs and more with ease. This tutorial is for projects that use another CSS framework (such as Bootstrap) and want to switch to Tailwind. If it's a new project, use create-nuxt-app as tailwind support is baked in.

Adding Tailwind into your project

Integrating with Nuxt is reasonably straightforward. All you need to do is create a few new files and modify your nuxt.config.js file.

To start with, add all your dependencies:

yarn add -D sass-loader node-sass tailwindcss nuxt-purgecss

Take note that they're all devDependencies and we're assuming you want to use SASS/SCSS in your project.

Now, for the Nuxt config:

export default {
 
 ...
 
 css: ['~/assets/scss/tailwind.scss'],
 
  modules: [
   'nuxt-purgecss'
  ],
 
  ...
 
  build: {
    extractCSS: true,
    postcss: {
      plugins: {
        tailwindcss: path.resolve(__dirname, './tailwind.config.js')
      }
    }
  },
  purgeCSS: {
    mode: 'postcss'
  }
}

These are all the modifications you need to make to your nuxt config. The css block adds the new Tailwind SCSS file; the modules block includes the nuxt-purgecss package and the build process now includes the changes required for purgeCSS to work.

Next, create a tailwind.config.js file:

// tailwind.config.js
module.exports = {
  prefix: '',
  important: false,
  separator: ':',
  theme: {},
  variants: {},
  plugins: []
}

At the moment this is an empty tailwind config. For more information on how to extend this and create your theme, see their docs.

And finally, all that's left is to create the new SCSS file that contains your tailwind CSS. In this case, we've put it in the ~/assets/scss/ folder, but this could live somewhere else if you'd prefer.

// ~/assets/scss/tailwind.scss
@tailwind base; 
 
@tailwind components; 
 
@tailwind utilities;

This file contains all the tailwind styles for your project. If you need to make any modifications, make the relevant changes in the config file and add the styles below @tailwind base;.

Wrapping up

As you can see, adding Tailwind to your existing Nuxt project is a simple 4-step process, but it adds tons of flexibility. Once you've learned all the classes, creating intricate and intuitive user interfaces becomes a painless and enjoyable task, and this is why I highly recommend Tailwind for your project(s)!