Use tailwind @apply in CSS modules in Next.js

Viewed 7316

I've setup tailwind with my Next.js site as per the official guide here: https://github.com/tailwindcss/setup-examples/tree/master/examples/nextjs

However, when I try and use the @apply method, in a CSS module on a component level, eg:

.container {
  @apply rows-span-3;
}

I get the following error:

Syntax error: @apply cannot be used with .rows-span-3 because .rows-span-3 either cannot be found, or its actual definition includes a pseudo-selector like :hover, :active, etc. If you're sure that .rows-span-3 exists, make sure that any @import statements are being properly processed before Tailwind CSS sees your CSS, as @apply can only be used for classes in the same CSS tree.

This is my postcss.config.js:

const purgecss = [
  '@fullhuman/postcss-purgecss',
  {
    content: ['./components/**/*.jsx', './pages/**/*.jsx'],
    defaultExtractor: content => content.match(/[\w-/:]+(?<!:)/g) || [],
  },
]

module.exports = {
  plugins: [
    'postcss-flexbugs-fixes',
    'postcss-import',
    'postcss-mixins',
    'postcss-calc',
    'postcss-extend',
    ['postcss-color-mod-function', {
      importFrom: [
        './assets/styles/vars.css',
      ],
    }],
    ['postcss-preset-env', {
      stage: 1,
      preserve: false,
      importFrom: [
        './assets/styles/vars.css',
      ],
    }],
    'tailwindcss',
    'autoprefixer',
    ...(process.env.NODE_ENV === 'production' ? [purgecss] : []),
    'postcss-nested',
  ],
}
2 Answers

I manage to make it work using this example link to tailwind doc

From the doc:

You have this module css

/*Button.module.css*/
.error {
  @apply bg-red-800 text-white;
}

Component file

//Button.js
import styles from './Button.module.css'

export function Button() {
  return (
    <button
      type="button"
      // Note how the "error" class is accessed as a property on the imported
      // `styles` object.
      className={styles.error}
    >
      Destroy
    </button>
  )
}

From the example, please notice the use of className={styles.error} instead of className="error"

I followed the example and I got @apply working with nextjs css modules using

.Card {
    @apply bg-blue-500;
}

This did not work with rows-span-3 as you had above, nor does it work with prefixed (md:) based on the docs it says: "will not work for inlining pseudo-class or responsive variants of another utility. Instead, apply the plain version of that utility into the appropriate pseudo-selector or a new media query"

Related