• Sage

How to Setup Tailwind CSS in Sage

I ❤️ designing in the browser. Luckily, utility-first CSS frameworks like Tailwind make it easier than ever. Here’s how you can get started using Tailwind CSS with Sage 9.

🎉 As of 9.0.2, Tailwind is now included as one of Sage’s CSS framework presets. You can use this guide if you’d like to install it manually. The Purgecss section is still very useful as well.

During the Sage install choose No Framework (you don’t have to, but it will help avoid naming conflicts + help reduce filesize), then complete the following:

1. Install Tailwind:

We need to require Tailwind as a dev dependency:

yarn add tailwindcss --dev

2. Initialize Tailwind

This generates a tailwind.js config file in styles directory:

./node_modules/.bin/tailwind init resources/assets/styles/tailwind.js

or if you have npx installed globally 🙌 (tip: you do have it if you are running npm 5.2.0+):

npx tailwind init resources/assets/styles/tailwind.js

3. Add Tailwind to the top of the PostCSS plugin list

In resources/assets/build/postcss.config.js add:

// ...
plugins: {
  tailwindcss: `${options.paths.assets}/styles/tailwind.js`,
  // ...
},

4. Add Tailwind directives to Stylelint ignoreAtRules list in package.json:

"ignoreAtRules": [
  // ...
  "tailwind",
  "apply",
  "responsive",
  "variants",
  "screen"
]

5. Add directives to main.scss:

/** Tailwind base styles – includes modified normalize.css */
@tailwind preflight;

/** Tailwind plugins – included in tailwind.js */
@tailwind components;

/**
 * Sage’s styles
 *
 * Placing these here allows you to use @apply
 * to apply Tailwind’s utilities
 */

/** Tailwind utilities – generated from config in tailwind.js */
@tailwind utilities;

Example

This example is a pure combination of Sage’s default main.scss and Tailwind’s recommended CSS structure:

@import "common/variables";
/**
 * This injects Tailwind's base styles, which is a combination of
 * Normalize.css and some additional base styles.
 *
 * You can see the styles here:
 * https://github.com/tailwindcss/tailwindcss/blob/master/css/preflight.css
 *
 * If using `postcss-import`, you should import this line from it's own file:
 *
 * @import "./tailwind-preflight.css";
 *
 * See: https://github.com/tailwindcss/tailwindcss/issues/53#issuecomment-341413622
 */
@tailwind preflight;

/** Import everything from autoload */
@import "./autoload/**/*";

/**
 * Import npm dependencies
 *
 * Prefix your imports with `~` to grab from node_modules/
 * @see https://github.com/webpack-contrib/sass-loader#imports
 */
// @import "~some-node-module";

/**
 * This injects any component classes registered by plugins.
 *
 * If using `postcss-import`, use this import instead:
 *
 * @import "tailwindcss/components";
 */
@tailwind components;

/**
 * Here you would add any of your custom component classes; stuff that you'd
 * want loaded *before* the utilities so that the utilities could still
 * override them.
 *
 * Example:
 *
 * .btn { ... }
 * .form-input { ... }
 *
 * Or if using a preprocessor or `postcss-import`:
 *
 * @import "components/buttons";
 * @import "components/forms";
 */
@import "common/global";
@import "components/buttons";
@import "components/comments";
@import "components/forms";
@import "components/wp-classes";
@import "layouts/header";
@import "layouts/sidebar";
@import "layouts/footer";
@import "layouts/pages";
@import "layouts/posts";
@import "layouts/tinymce";

/**
 * This injects all of Tailwind's utility classes, generated based on your
 * config file.
 *
 * If using `postcss-import`, you should import this line from it's own file:
 *
 * @import "./tailwind-utilities.css";
 *
 * See: https://github.com/tailwindcss/tailwindcss/issues/53#issuecomment-341413622
 */
@tailwind utilities;

/**
 * Here you would add any custom utilities you need that don't come out of the
 * box with Tailwind.
 *
 * Example :
 *
 * .bg-pattern-graph-paper { ... }
 * .skew-45 { ... }
 *
 * Or if using a preprocessor or `postcss-import`:
 *
 * @import "utilities/background-patterns";
 * @import "utilities/skew-transforms";
 */

A simpler setup

/** Tailwind base styles */
@tailwind preflight;

/** Import everything from autoload */
@import "./autoload/**/*";

/** Tailwind plugins */
@tailwind components;

/** Your own components – checkout @apply */

/** Tailwind utilities */
@tailwind utilities;

/** Define custom utilities */

Check out the Tailwind docs for notes on CSS structure.

6. Add Purgecss for unused CSS removal (optional)

  1. Add Purgecss to Sage.
  2. Once you’ve successfully added Purgecss, you will need to complete an addition step to make sure Purgecss can extract Tailwind’s classes properly. Luckily, Tailwind has a guide in their docs to add a custom Purgecss extractor.

Example

In webpack.config.optimize.js:

'use strict'; // eslint-disable-line

const { default: ImageminPlugin } = require('imagemin-webpack-plugin');
const imageminMozjpeg = require('imagemin-mozjpeg');
const glob = require('glob-all');
const PurgecssPlugin = require('purgecss-webpack-plugin');

const config = require('./config');

class TailwindExtractor {
  static extract(content) {
    return content.match(/[A-z0-9-:\/]+/g) || [];
  }
}

module.exports = {
  plugins: [
    new ImageminPlugin({
      optipng: { optimizationLevel: 7 },
      gifsicle: { optimizationLevel: 3 },
      pngquant: { quality: '65-90', speed: 4 },
      svgo: { removeUnknownsAndDefaults: false, cleanupIDs: false },
      plugins: [imageminMozjpeg({ quality: 75 })],
      disable: (config.enabled.watcher),
    }),
    new PurgecssPlugin({
      paths: glob.sync([
        'app/**/*.php',
        'resources/views/**/*.php',
        'resources/assets/scripts/**/*.js',
      ]),
      extractors: [
        {
          extractor: TailwindExtractor,
          extensions: ["js", "php"]
        }
      ],
    }),
  ],
};

And there you go — you’re all setup. Just run yarn start,1 pop open tailwind.js to define your design system, and start building! 🎉



1 You will notice a Webpack warning when running yarn start. There is nothing going wrong with the compiling of your styles, but this is a known issue with the resolve url Webpack loader. If you comment it out in the Webpack config file, the error will no longer appear, however, an error will persist in the browser console since this breaks source maps. Since you are using Tailwind — which generates CSS via a JavaScript config file — you don’t really need source maps, so you can go even further and remove the sourceMap option form the css/postcss/sass loaders. It does suck, but using a utility CSS framework you’ll notice you will be spending a lot less time in your stylesheets and more time in the markup designing.

🤷‍♀️

Join the discussion on Roots Discourse

Join over 5,700 subscribers on our newsletter to get the latest Roots updates, along with occasional tips on building better WordPress sites.

Looking for WordPress plugin recommendations, the newest modern WordPress projects, and general web development tips and articles?

“Easily the best WordPress email I get.” Colin OBrien

Ready to checkout?