11. Pass themes as a plugin option
đ TL;DR
- We could stop right there, but letâs look at another way to pass the color themes to our plugin
- Letâs use
plugin.withOptions()
from the Tailwind Plugin API!
âŹď¸ Skip to the challenge
đ˘ Background
At this point, our plugin is fully functional, and can be used in any project using Tailwind CSS.
While passing the color themes via a custon key in the Tailwind config works great, there is another approach worth considering.
And that is to pass the color themes to the plugin as an option, via the plugin.withOptions()
API.
Passing color themes as a plugin option
When you register a plugin in your Tailwind configâs plugins
array, you can pass options to a given plugin:
module.exports = {
theme: {},
plugins: [
- multiThemePlugin,
+ multiThemePlugin({
+ themes: {
+ base: { ... }
+ }
+ })
]
}
The plugin code will need to be updated to use plugin.withOptions
before this syntax works properly.
Why do that?
I see two benefits from this approach over defining the color themes inside a custom config key:
-
Avoiding accidental namespace collisions. When you define a new custom key, youâre claiming a little âpiece of landâ within your Tailwind config.
What if you work on a large project with many other teams, and someone else brought some customisations to the exact same custom theme key?
-
Defining your color themes as an option passed to the plugin feels more collocated. You literally register the plugin and provide it some themes in the very same place.
Both approaches are totally valid, and have their trade-offs.
Accessing the color themes via the theme()
function outside of the plugin might be something you want, and in that case youâd be better off defining your themes in a custom key, like we just did.
Itâs all about understanding the tools and the trade-offs!
đ Your challenge đ
In the Tailwind Play belowâŚ
-
Move the color themes definition away from the custom config key. Instead, pass those directly to the plugin.
-
Update the plugin code to use the
plugin.withOptions
API.
Youâll find more hints within the Play.
âď¸ Good luck!
Start challenge