TailwindCSS in NextJS
You know when you're trying to stitch together packages that just don't work? You've tried several different configs, and you start losing track of what you tried? I'm planting my stake. I'm going to be using NextJS with Tailwind again so this is how you stitch these together.
I've spent my spare time over the last several days working out how to get TailwindCSS working in NextJS with PurgeCSS running. I recently created a web app for my daughters exploring browser voice recognition. They can speak the letters displayed on the screen and get points.
Step by Step
Get that NextJS goodness:
npx create next-app
Install some of those dependencies:
npm install tailwindcss postcss-import autoprefixer @fullhuman/postcss-purgecss --save
Setup your PostCSS config postcss.config.js
module.exports = {
plugins: [
"postcss-import",
"tailwindcss",
"autoprefixer"
]
};
Create your styles
/* purgecss start ignore */
@import"tailwindcss/base";
@import"tailwindcss/components";
/* purgecss end ignore */
@import"tailwindcss/utilities";
Make sure you import your styles into _app.js
import '../styles/globals.css'
import '../styles/index.css'
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
export default MyApp
Add to the postcss.config.js
const purgecss = [
"@fullhuman/postcss-purgecss",
{
content: ["./components/**/*.js", "./pages/**/*.js"],
defaultExtractor: content => content.match(/[\w-/:]+(?<!:)/g) || []
}
];
module.exports = {
plugins: [
"postcss-import",
"tailwindcss",
"autoprefixer",
...(process.env.NODE_ENV === "production" ? [purgecss] : [])
]
};
The plugins have to be imported as strings, not as requires like the documentation. We also don't run PurgeCSS in development because it is pretty slow.
Key Differences
The key differences from https://github.com/tailwindlabs/tailwindcss-setup-examples/tree/master/examples/nextjs is the purgecss ignore. I had the application working in development, but on production it was ignoring element styles. I had a bg-color on the body tag and that was completely wiped. If I didn't use purge, my css file was 180kb!!!
We are using strings in the postcss.config.js.
Other than these changes, you should be good to go. I should probably extract this is a preconfigured starter.