ben-rogerson / twin.macro

🦹‍♂️ Twin blends the magic of Tailwind with the flexibility of css-in-js (emotion, styled-components, solid-styled-components, stitches and goober) at build time.
MIT License
7.92k stars 183 forks source link

Add @apply support in plugins #770

Closed ben-rogerson closed 1 year ago

ben-rogerson commented 1 year ago

This PR adds support for the usage of @apply to create tailwindcss plugins.

Use twin classes including class groups (eg: first:(block mt-4)) to define your plugin styles:

// tailwind.config.js

// Usage: `tw("block bg-black", "[.comma-divided-sets]:visible")`
const tw = (...classes) => {
  const result = {}
  result[`@apply ${classes.join(" ")}`] = {}
  return result
}

module.exports = {
  theme: { colors: { primary: "#F07E22" } },
  plugins: [
    ({ addBase, addComponents, addUtilities }) => {
      addBase({
        // Add colors from your theme
        "html, body": tw("selection:text-primary"),
      })

      addComponents({
        ".component": tw(
          // Use arbitrary classes
          "content-[arbitrary value] [.arbitrary-variant]:content [content:arbitrary-property]]"
        ),
      })

      addUtilities({
        // Use bracketed groups to style multiple classes at once
        ".utility": tw("first:(block mt-4)"),
      })
    },
  ],
}

Original feature reference: https://github.com/tailwindlabs/tailwindcss/discussions/2049

ben-rogerson commented 1 year ago

I've also made Twin warn us when using a class that doesn't exist within @apply - rather than silently fail like the tailwindcss default.