Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use tailwind @apply in CSS modules in Next.js

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',
  ],
}
like image 516
bravokiloecho Avatar asked May 13 '20 10:05

bravokiloecho


People also ask

Can I use CSS modules with Tailwind?

Using tailwind in css modules seems like added complexity with little benefit. Readability is lost due to everything being inline. Utility classes are lost and converted into simple css which results in the same bundle size.


1 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"

like image 187
Ponleu Avatar answered Nov 03 '22 14:11

Ponleu