Add Imports to Tailwind CSS with PostCSS

I have been enjoying Tailwind CSS as my main CSS tool for building components. It's an amazing tool for building your own components. It reminds me of what I love about Foundation. Core reusable styles to build custom reusable components from.

It's important to note I only recommend these tools if you are putting time & effort into custom design work. If all you want is pre-built components, use an off the shelf component system that looks great. There are tons of other tools better suited for that. Bootstrap being the most popular.

The Tailwind CSS documentation is great. One thing missing by default was how to use @import. The great thing about Tailwind is this is rarely needed. In fact I've done multiple production projects & have yet to need it. But I had some components that needed some custom CSS and I wanted to separate my style files.

Since I was using PostCSS already & didn't want to add Sass unless I had to, I went searching for a tool. I found PostCSS-Import. I added with npm install --save-dev postcss-import. Then I added it to my postcss.config.js file.

const purgecss = require('@fullhuman/postcss-purgecss')({
  content: [
    './dist/*.html'
  ],

  // Include any special characters you're using in this regular expression
  defaultExtractor: content => content.match(/[\w-/:]+(?<!:)/g) || []
})
module.exports = {
  plugins: [
    require('postcss-import'),
    require('tailwindcss'),
    require('autoprefixer'),
    require('cssnano')({
      preset: 'default'
    }),
    ...[purgecss]
  ]
}

The above is a common Tailwind CSS setup with Post CSS based off the Tailwind CSS docs. PostCSS-Import recommends it being the first plugin. My initial style.css looked like below:

@tailwind base;
@tailwind components;
@tailwind utilities;

Now with imports I was able to adjust it like this:

@import "./style.base.css";
@import "../components/ArticlePreview/style.css";
@tailwind components;
@tailwind utilities;

I moved @tailwind base; into my style.base.css file:

/* style.base.css */

@tailwind base;
body {
  @apply p-2;
  @apply m-auto;
}

h1 {
  @apply text-2xl;
  @apply mb-1;
}

Tailwind CSS recommends that @tailwind base; should be the first line in your CSS. Putting it in my first file & base import seemed to make the most sense. I can then import all my other custom styles next as recommended per Tailwind CSS docs.

One Last Thing...

If you have a question or see a mistake, please comment below.

If you found this post helpful, please share it with others. It's the best thanks I can ask for & it gives me momentum to keep writing!

Matt Ferderer
Software Developer focused on making great user experiences. I enjoy learning, sharing & helping others make amazing things.
Let's Connect