loading...

Starter Template #1 | NextJS + Tailwind CSS

pika11 profile image Alejandro Foronda Updated on ・2 min read

This template is a starter for those looking to use Tailwind CSS in a NextJS project.

CodeSandbox
Github

Setup Description

NextJS

Instructions

  1. npm install --save @zeit/next-css
  2. Create a nextjs.config.js in your project if you don't have it already.
  3. Import the plugin to your project.
// next.config.js
const withCSS = require('@zeit/next-css')
module.exports = withCSS({})

Tailwind

Since NextJS already uses PostCSS we just need to create a postcss.config.js to load the required plugins for tailwind to work properly and efficiently.

To Work Properly

  • tailwind Tailwind npm package: this will load the necessary css.
  • autoprefixer Autoprefixer npm package: this package will add vendor prefixes to CSS rules.

To Load Efficiently

  • cssnano cssnano npm package: this package will minify the css output.
  • purgecss purgecss npm package: this package will traverse your code and remove all unused css classes that tailwind generates.

Instructions

  1. npm install --save tailwindcss autoprefixer purgecss cssnano
  2. Create a postcss.config.js in your project if you don't have it already.
  3. Import the plugins to your project, the plugins for optimization should only be loaded in production.
// postcss.config.js

//load purgecss 
const purgecss = require('@fullhuman/postcss-purgecss')({

    // Specify the paths to all of the template files in your project 
    content: [
        './pages/*.js', './pages/*.tsx',
        './components/*.js', './components/*.tsx' 
    ],

    // Include any special characters you're using in this regular expression
    // Recommended algorithm by tailwind but you're free to change it to your needs
    defaultExtractor: content => content.match(/[\w-/:]+(?<!:)/g) || []
});

// load cssnano
const cssnano = require('cssnano')({
    preset: 'default',
});



module.exports = {
    plugins: [
        //load tailwindcss
        require('tailwindcss'),
        //load autoprefixer
        require('autoprefixer'),
        //only use purgecss and cssnano on production builds
        ...process.env.NODE_ENV === 'production'
            ? [purgecss, cssnano]
            : []
    ]
};

Posted on Jan 1 by:

pika11 profile

Alejandro Foronda

@pika11

Hi! I'm Alejandro, I'm a Software Engineer who loves web technologies. I'm an education passionate looking for better ways to learn and make technology accessible to everyone.

Discussion

markdown guide
 

Exactly what I have been looking for :)