Categories
Code

Get up and running with TailwindCSS and Next.JS

TailwindCSS is a popular utility-first CSS framework which has first-class support in Next.JS. I’ve seen some really crazy configurations scattered throughout Github and Reddit that are completely unnecessary. Here’s a simple way to add TailwindCSS to your Next.JS apps.

TL;DR: View the codebase on Github and the front-end at https://nextjs-tailwindcss-example.vercel.app/


First, create a new Next.JS app (or skip this if you already have one):

yarn create next-app

Add the following NPM packages: tailwindcss, postcss-preset-env, and postcss-flexbugs-fixes to your app:

yarn add --dev tailwindcss postcss-preset-env postcss-flexbugs-fixes

In the root directory, create a postcss.config.js file

// ./postcss.config.js

module.exports = {
  plugins: [
    'tailwindcss',
    'postcss-flexbugs-fixes',
    [
      'postcss-preset-env',
      {
        autoprefixer: {
          flexbox: 'no-2009'
        },
        stage: 3,
        features: {
          'custom-properties': false
        }
      }
    ]
  ]
}

Note: because Next.JS already includes postcss.config.js behind the scenes, we’ll need to bring those settings into our file too.

Now create a tailwind.config.js file in the root directory:

// ./tailwind.config.js

module.exports = {
  purge: ['./components/**/*.js', './pages/**/*.js'],
  theme: {
    extend: {}
  },
  variants: {},
  plugins: []
}

Note: TailwindCSS now includes PurgeCSS, and it’s easy to configure as you can see above.

Next, create a folder named /styles, then create a file named index.css to place inside it. Add the following code:

// ./styles/index.css

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

/* EXAMPLE */
body {
  @apply bg-black text-white;
}

Note: the code above, will turn the body background to black and the font color to white. It’s for example purposes and can be deleted.

Now we have to import the CSS file. To do that, create _app.js in /pages:

// ./pages/_app.js

import '../styles/index.css'

const App = ({Component, pageProps}) => <Component {...pageProps} />

export default App

Note: adding the CSS file to _app.js means our style-sheet will be available on every page.

Now spin up the dev server:

yarn dev

That’s it! You can view this example on Github (or view the official example on Next.JS’s Github) and the front-end at https://nextjs-tailwindcss-example.vercel.app/.

Did this tutorial help? I’d love to know in the comments below or on Twitter. Thanks for reading!

By Greg Rickaby

Director of Engineering @WebDevStudios / Author & Editor @Wiley

Leave a Reply