Access to your Tailwind theme on the go!
Hey, today I'd like to share a new tool I've developed: tailwindcss-expose-colors
. It's a useful piece of code that I think many of you will appreciate for its practicality and simplicity.
#Contents
#An Open-Source Beginning
This journey started with a simple Gist, but as I delved deeper, I saw the potential to evolve this snippet into a more robust package, thus tailwindcss-expose-colors
was born. This tool is all about bringing a touch of convenience and efficiency to your workflow when working with Tailwind CSS.
#The mechanics of tailwindcss-expose-colors
Here's the TL/DR: tailwindcss-expose-colors
lets you… Guess what? Expose selected colors from your Tailwind theme as CSS variables. The idea is simple: to make it easier to use your Tailwind theme colors directly in your CSS and even manipulate them in JavaScript.
#Here's a Look at the Code
The plugin is built with TypeScript and hooks into Tailwind's plugin API. Here's a snapshot of the main function:
It then filters and maps your theme's colors based on your configuration (tailwind.config.ts
) and injects them as CSS variables into your project.
#Customizable, simple, and lightweight
With tailwindcss-expose-colors
, you can specify which colors and shades to expose and even set your preferred variable prefix. Here's an example of setting it up in tailwind.config.ts
:
#Simple Setup
#Advanced Setup
#Practical Application
Once everything is set up, you can use these colors in your CSS, like this:
This integration makes it straightforward to adapt and apply colors to various aspects of your web projects.
#In a "real" scenario
This utility began as a simple itch that I had while thinking about how to set a color variable based on a specific condition in JS so that all of the children could be styled accordingly. This is the original snippet:
To clarify, this is a simplified version of the original code running in production. That said, this is the use I have for it:
And that's it, now I have my theme colors matching with the rest of the system even if I change them afterwards, which didn't happen in my last approach just copying the hex.
With this plugin, I extended the original functionality; now we have R, G, B
values, so the opacity is also a customizable value for rgba(var(--tw-red-500), 0.5)
, and scoped the config so the exported variables are only the essentials you'll need, cause those can weigh quite a lot on the CSS bundle.
#Wrapping Up
tailwindcss-expose-colors
is a nifty little addition to your Tailwind CSS toolkit. It's about making life a bit easier and your code a bit cleaner. So, give it a whirl in your next project and see how it fits!
I'm open to feedback and suggestions, so feel free to share your thoughts and experiences. Here's to making our development journey a bit more enjoyable, one handy utility at a time!