Next.js Tailwindcss with SASS example

Tailwind CSS is a highly customizable, low-level CSS framework that gives you all of the building blocks you need to build bespoke designs without any annoying opinionated styles you have to fight to override.

In this blog we will learn about how we can setup tailwind and sass with next.js. Let’s install Next js, react and react dom

mkdir next-project && cd next-project
npm init --yes
npm install next react react-dom

Now inside of package.json

"scripts": {
  "dev": "next dev",
  "build": "next build",
  "start": "next start"
}

Install Sass

Next.js has built in support for sass. Before you can use Next.js’ built-in Sass support, be sure to install sass:

npm install sass

Install tailwind and post-css

Let’s install tailwind and the required packages for post-css as dev dependency.

npm install tailwindcss@latest postcss-flexbugs-fixes postcss-preset-env postcss-import precss -D

Postcss config

Let’s create a file called postcss.config.js and add the following configurations in the root of your project

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

Next.js config

Let’s create a file called next.config.js and add the following configurations in the root of your project

const path = require('path')
module.exports = {
	trailingSlash: false,
	webpackDevMiddleware: config => {
		config.watchOptions = {
			poll: 1000,
			aggregateTimeout: 300
		}

		return config
	},
	sassOptions: {
		includePaths: [path.join(__dirname, 'styles')]
	}
}

Tailwind Config

Let’s create a tailwind config file by running the following command.

./node_modules/.bin/tailwind init

Notice that we are adding the path for the files that are to be purged so that only those tailwind css is produced in production that is actually used by those components or pages.

module.exports = {
	purge: [
		'./src/components/**/*.js',
		'./pages/**/*.js'],
	theme: {
		extend: {},
	},
	variants: {},
	plugins: [
		require( 'tailwindcss' ),
		require( 'precss' ),
		require( 'autoprefixer' )
	]
}

Now create a sass file called index.scss in a styles directory and add the following

@import "~tailwindcss/base";
@import "~tailwindcss/components";
@import "~tailwindcss/utilities";

Now import this sass file in _app.js

import '../src/styles/index.scss'

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

export default MyApp

You can see a working example in my:

That’s all folks!

One thought on “Next.js Tailwindcss with SASS example

Leave a Reply