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('./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.

PurgeCSS is included in Tailwind CSS. You only have to update your Tailwind config and you're good to go:

// tailwind.config.js

module.exports = {
  purge: ['./src/**/*.js']

It 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!