cssnext.jstailwind-css-4

Usage of Tailwind 4 @apply directive in NextJS React .module.css


Sorry for this lame question - I am quite new in tailwind and the utilities around it. What I want to achieve is to write some local styles for my components using tailwind and @apply. I use the latest nextJS with latest tailwindcss (v4) how can I use the @apply directive in my local MyComponent.module.css file?

I mean I have a MyComponent.tsx like this:

import styles from "./MyComponent.module.css";
export default function MyComponent() {
   return <div className={styles.green}>Green Text Here</div>
}

And in ./MyComponent.module.css I would write something like this:

.green {
  @apply text-green-500
}

What package I need, and what setup to achieve this?

Note: in my layout.tsx I include tailwindcss as usual:

import "@/styles/globals.scss";

where globals.scss looks as:

@import "tailwindcss";

Unfortunately - I got compiler error during npm run build, saying

| Error: Cannot apply unknown utility class: text-green-500

however this classname works directly in components.


Solution

  • Deprecated preprocessors support

    Please note that as of v4, TailwindCSS officially does not support SCSS. Therefore, any issues arising from SCSS usage can typically be resolved simply by avoiding SCSS altogether.

    CSS Modules Compatibility

    As of TailwindCSS v4, the official recommendation is to avoid using @apply in connection with external modules. This can lead to excessive duplication and a larger compiled CSS output. See posts from one of the TailwindCSS creators for more details:

    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.

    Instead, use references to the appropriate variables:

    .green {
      color: var(--color-green-500);
    }