cssnext.jstailwind-csspostcsstailwind-css-4

Make TailwindCSS V4 not ignore CSS files


ENVIRONMENT

DESCRIPTION

Recently all my projects were done using TailwindCSS together with .module.css. Despite official recommendations which states following:

CSS modules Tailwind is compatible with CSS modules and can co-exist with them if you are introducing >Tailwind into a project that already uses them, but we don't recommend using CSS modules and >Tailwind together if you can avoid it.

I was using this pair together because I like readability, and putting all classes in one line makes it so hard to read.


In latest TW upgrade (v4.1) they state that CSS files are no longer automatically detected:

Which files are scanned - Tailwind will scan every file in your project for class names, except in the following cases:

  • Files that are in your .gitignore file
  • Binary files like images, videos, or zip files
  • CSS files
  • Common package manager lock files

Together with this information, they provide us ways how to detect files by explicitly registering files. That's what I tried to do, but still nothing is working.

CODE

src/app/globals.css:

@import "tailwindcss";
@source "../";


body, html {
  @apply w-dvw h-dvh;
  @apply p-0 m-0;
}

src/app/layout.tsx:

import "./globals.css";

export default function RootLayout({
   children,
}: Readonly<{
   children: React.ReactNode;
}>) {
   return (
      <html lang="en">
         <body>{children}</body>
      </html>
   );
}

src/app/page.tsx:

import s from './page.module.css';

export default function Home() {
  return <main className={s.main}></main>
}

src/app/page.module.css:

.main {
   @apply w-full h-full bg-slate-700;
}

And on output I don't even see that class is being assigned to the element:

enter image description here

What's interesting: if I remove bg-slate-700 and leave just w-full h-full - it works and it assigns styles.


Solution

  • You can use TailwindCSS directives only in the global CSS file. If you want to use them in other modules or locations, you need to add an @reference directive at the top of the file pointing to the main global.css:

    @reference "./global.css";
    
    .main {
       @apply w-full h-full bg-slate-700;
    }
    

    If you don't need the custom @theme declarations from your own global.css and only want access to the default TailwindCSS classes, then simply use:

    @reference "tailwindcss";
    
    .main {
       @apply w-full h-full bg-slate-700;
    }
    

    Related: