'Tailwind: How to make @apply work for custom CSS class?

Say you have a basic project setup:

@tailwind base;
@tailwind components;
@tailwind utilities;

And you want to add a basic utility that uses CSS that's not part of tailwinds default library:

@layer utilities {
  .will-change-transform {
    will-change: transform;
  }
}

or

@layer utilities {
  .ease {
    transition: ease;
  }
}

and you want to be able to @apply it to a custom class down the line without receiving an error:

.my-component {
  @apply block hover:scale-110 w-full ease will-change-transform
}

How would you do this?



Solution 1:[1]

I can't say for sure without seeing your environment or the error you were receiving, but the documented way of circumventing these issues is to define your classes in your tailwind config file:

// tailwind.config.cjs
const plugin = require('tailwindcss/plugin')

module.exports = {
  // ...

  plugins: [
    plugin(function ({ addComponents, theme }) {
      addComponents({
        '.will-change-trans': { // `will-change-transform` is now included in Tailwind CSS 3.0 so using alternative class name for this example
          willChange: 'transform'
        },
        '.ease': {
          transition: 'ease'
        },
      })
    })
  ]

}

then you can @apply these classes anywhere as if they were built in.

(I realize that this issue is probably no longer relevant to you, but I found it while searching so this is for anyone else stumbles upon this question!)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jspn