DEV Community

Cover image for The Correct Way of Adding Tailwind to Your Next.js App
Karmasakshi Goyal
Karmasakshi Goyal

Posted on • Originally published at karmasakshi.Medium

The Correct Way of Adding Tailwind to Your Next.js App

I list steps to add Tailwind to a Next.js app and highlight what some are doing wrong.

TL;DR

The correct way of adding Tailwind to a Next.js app is by following the steps mentioned in the Tailwind Docs.

Steps

Navigate into the Next.js app directory and follow these steps:

  1. Install Tailwind dependencies:
    npm install tailwindcss@latest postcss@latest autoprefixer@latest

  2. Generate tailwind.config.js and postcss.config.js:
    npx tailwindcss init -p

  3. Configure Tailwind to remove unused styles from production builds:

// ./tailwind.config.js 
module.exports = {
  purge: ['./pages/**/*.jsx'],
  ...
} 
Enter fullscreen mode Exit fullscreen mode
  • Besides ./pages, ensure all paths of components that use Tailwind are also added; e.g. purge: ['./pages/**/*.jsx', './components/**/*.jsx'],

  • Ensure the extension is appropriate; e.g. your file extension may be different if you’re writing TypeScript: purge: ['./pages/**/*.tsx', './components/**/*.tsx'],

  1. Include Tailwind styles along with your own in the global stylesheet:
// ./styles/global.css
@tailwind base;
@tailwind components;
// Add Tailwind's @apply styles here
@tailwind utilities;
// Add other global styles below
html {
  ...
}
body {
  ...
}
Enter fullscreen mode Exit fullscreen mode
  1. Add the global stylesheet to all your pages via ./pages/_app.jsx:
// ./pages/_app.jsx
import '../styles/global.css';

function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}

export default MyApp;
Enter fullscreen mode Exit fullscreen mode

What Some Are Doing Wrong

Besides referring to an older, outdated article, you could be doing the following mistakes:

  1. Saving Tailwind dependencies as devDependency:
    Tailwind is a collection of classes that go into your production app. They are not used for developing the app, but are a part of one. In an ideal scenario, you would want to skip installing devDependency in a CI/CD process to save bandwidth and time. Your app won’t build then.

  2. Adding additional dependencies:
    Tailwind doesn’t need any other dependency like postcss-preset-env, @fullhuman/postcss-purgecss or others.

  3. Adding a CSS reset along with Tailwind:
    Tailwind already uses Preflight as the base, which resets browser styles to ensure consistent look across all browsers. However, if you prefer to use your own reset, you should first turn Preflight off:

// tailwind.config.js
module.exports = {
  corePlugins: {
    preflight: false,
  },
  ...
}
Enter fullscreen mode Exit fullscreen mode

Cheers!

Top comments (0)