How to configure Tailwind in a Next.js project

Stewart Granger Flores - 11 Noviembre, 2020

Tailwind CSS Banner
💡
Now you can use tailwind in Next.js using the following flag when you create the project. And you save the below 😋.
npx create-next-app -e with-tailwindcss

Upgrade 2021

1.- Install TailwindCSS

After creating your Next.js project with create-next-app you need to install tailwind in your project. For this we will use

    npm install tailwindcss -D
    

2.- Create the Tailwind configuration file

The next step is to create the Tailwind configuration file, which is located in the root path of the project and is named tailwind.config.jsand in addition, it creates the complete tailwind structure.

    npx tailwindcss init --full
    

3.- Create the Postcss file

Now we need to create the postcss.config.js file and inside paste the following code

    module.exports = {
    plugins: ["postcss-import", "tailwindcss", "autoprefixer"],
    };

We continue to install postcss-preset-env which helps convert your CSS code into something that all browsers can understand when building your project.


    npm install postcss-preset-env -D
    

4.- Tailwind.css

Now we will create inside the styles folder created by Next.js a file named tailwind.css and inside we will put the following:


    /* purgecss start ignore */
    @tailwind base;
    @tailwind components;
    /* purgecss end ignore */
    @tailwind utilities;

and we import it in _app.js so that it is contemplated in each page that we make in our project.


    import "../styles/globals.css";
    import "../styles/tailwind.css"; // <---- aquí

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

    export default MyApp;

5.- PostCSS PurgeCSS, Autoprefixer, PostCSS Import

Now in order to minimize the amount of CSS that is created in our build, we will use PostCSS PurgeCSSwhose task is to identify ALL the CSS that we are not using in our project and purge it, to make a smaller bundle.


    npm install @fullhuman/postcss-purgecss -D
    npm install autoprefixer
    npm install postcss-import

And that's it.

With all this, you should now have your project working with TailwindCSS.🎉