Bootstrapping Next.js with TailwindCSS and TypeScript

Saurish Srivastava

May 15, 2021

A banner

I've recently been utilizing TypeScript for a few of my projects, and I wanted to create a guide on bootstrapping boostrap a Next.js app with TailwindCSS.

Creating a Next.js application

yarn create next-app [App Name]
# or
npx create-next-app [App Name]
cd [App Name]

Adding TypeScript

touch tsconfig.json
yarn add typescript @types/react @types/node
# or
npm install typescript @types/react @types/node

Now start your development server:

yarn dev
# or
npm run dev

Next.js will automatically recognize the tsconfig.json file and write the default configurations, with some custom compiler options.

Now you're ready to use TypesScript, so you can change your _app.js and index.js files to _app.tsx and index.tsx!

Adding TailwindCSS

# if you're on Next.js v10:
npm install -D tailwindcss@latest postcss@latest autoprefixer@latest
# or
yarn add -D tailwindcss@latest postcss@latest autoprefixer@latest

# if you're on Next.js v9 or older:
npm install -D tailwindcss@npm:@tailwindcss/postcss7-compat postcss@^7 autoprefixer@^9
# or
yarn add -D tailwindcss@npm:@tailwindcss/postcss7-compat postcss@^7 autoprefixer@^9

Next, we need to add the tailwindcss.config.js and postcss.config.js files:

npx tailwindcss init -p

We need to edit the tailwindcss.config.js:

  // tailwind.config.js
  module.exports = {
    purge: [],
    darkMode: false, // or 'media' or 'class'
    theme: {
      extend: {},
    },
    variants: {
      extend: {},
    },
    plugins: [],
  }

Change purge:[] to purge: ['./pages/**/*.{js,ts,jsx,tsx}', './components/**/*.{js,ts,jsx,tsx}']:

  // tailwind.config.js
  module.exports = {
   /** purge: [], delete this line **/
   purge: ['./pages/**/*.{js,ts,jsx,tsx}', './components/**/*.{js,ts,jsx,tsx}'],
    darkMode: false, // or 'media' or 'class'
    theme: {
      extend: {},
    },
    variants: {
      extend: {},
    },
    plugins: [],
  }

We now need to embed TailwindCSS into our JS/CSS – there are two ways:

The first is to embed it directly into the JS app itself:

// pages/_app.js
import 'tailwindcss/tailwind.css'
// remove: import '../styles/globals.css'

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

export default MyApp

The second way is to embed it into your CSS:

/* ./styles/globals.css */
@tailwind base;
@tailwind components;
@tailwind utilities;

That's it! You're Done!