Published  | 3 min read

How to properly setup Tailwind CSS for Gatsby using Sass

I recently had to setup a new project with Gatsby and I decided that it's time to try out Tailwind CSS on a bigger project. So here's a short tutorial with all steps to get up and running:


1. Install dependencies

Install the needed dependencies with npm or yarn for the Gatsby project. Note that Tailwind will be installed as dev dependency.

# npm
npm install node-sass gatsby-plugin-sass
npm install tailwindcss --save-dev

# yarn
yarn add node-sass gatsby-plugin-sass
yarn add tailwindcss --dev

2. Create a Tailwind Config

This step is optional but is necessary if you want to customize your Tailwind installation. Run the following command to create the config file using npx.

npx tailwindcss init

This will create the tailwind.config.js at the root of your project. Read more about configuring Tailwind on the official docs.


3. Update Gatsby Config

Add the gatsby-plugin-sass to your gatsby-config.js with Tailwind and its config as PostCSS plugins.

// gatsy-config.js

module.exports = {
  plugins: [
    {
      resolve: 'gatsby-plugin-sass',
      options: {
        postCssPlugins: [
          require('tailwindcss'),
          require('./tailwind.config.js') // optional
        ]
      }
    }
  ]
}

Now you're able to use all Tailwind classes in your SCSS files by using the @apply directive provided by Tailwind.


4. Import Tailwind styles

Create a SCSS file called global.scss and import all Tailwind styles.

// global.scss

@import 'tailwindcss/base';
@import 'tailwindcss/components';
@import 'tailwindcss/utilities';

Include the SCSS file in your gatsby-browser.js file to have the styles available globally.

// gatsby-browser.js

import './src/scss/global.scss';

You can now use the Tailwind classes to style your site! 🎉


5. Setup PurgeCSS

You're almost done. It's highly recommended to use PurgeCSS, otherwise you'll end up with a lot of unused Tailwind classes after building your project. And that's just unnecesseary weight.

First, install gatsby-plugin-purgecss as a new dependency.

# npm
npm install gatsby-plugin-purgecss

# yarn
yarn add gatsby-plugin-purgecss

And again, add the newly installed plugin to your gatsby-config.js. It's important to put the plugin after the gatsby-plugin-sass plugin.

// gatsy-config.js

module.exports = {
  plugins: [
    {
      resolve: 'gatsby-plugin-sass',
      options: {
        ...
      }
    },
    {
      resolve: `gatsby-plugin-purgecss`,
      options: {
        tailwind: true
      }
    }
  ]
}

The plugin will now remove unused CSS from the SCSS files. Learn more about all the available options of PurgeCSS.


And that's it, you should now have a great setup with Gatsby featuring Tailwind. 😎 Happy styling!