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:
Install Tailwind dependencies:
npm install tailwindcss@latest postcss@latest autoprefixer@latest
Generate
tailwind.config.js
andpostcss.config.js
:
npx tailwindcss init -p
Configure Tailwind to remove unused styles from production builds:
// ./tailwind.config.js
module.exports = {
purge: ['./pages/**/*.jsx'],
...
}
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'],
- 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 {
...
}
-
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;
What Some Are Doing Wrong
Besides referring to an older, outdated article, you could be doing the following mistakes:
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 installingdevDependency
in a CI/CD process to save bandwidth and time. Your app won’t build then.Adding additional dependencies:
Tailwind doesn’t need any other dependency likepostcss-preset-env
,@fullhuman/postcss-purgecss
or others.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,
},
...
}
Cheers!
Top comments (0)