Pro Tailwind

10. Define themes in Tailwind config

šŸ‡ TL;DR

  • The last ā€œhardcodedā€ thing is how the color themes are made available to the plugin
  • Letā€™s allow users to define their own color themes in the Tailwind config!

ā¬‡ļø Skip to the challenge


šŸ¢ Background

Whoaaa. At this point, our plugin is pretty badass.

The one weird thing remaning is how the color themes are made available to the plugin. Right now, weā€™re defining those themes inside the plugin.

It would be way more useful to allow users of our plugin to define the themes themselves, and make our plugin accept that data.

We can do this in a couple of different ways, and weā€™ll start by doing it via a custom Tailwind config theme key.

Adding a custom key to our Tailwind config

In our Tailwind configā€™s theme object, we can create a new key, which weā€™ll be able to read from within the plugin.

Since our plugin is called multiTheme, how about creating a multiTheme key in our theme object in the config?

// tailwind.config.js
module.exports = {
  theme: {
    // We can define a custom theme key for our color themes
    multiTheme: {
      base: {
        primary: { ... },
        secondary: {... }
      },
      rainforest: { ... },
      candy: { ... }
    },
  },
}

Weā€™ll be able to access this key anwyere where Tailwindā€™s theme() function works.

News flash - itā€™s almost everywhere. You can use it in your CSS, in your HTML andā€¦

ā€¦in JavaScript with the Plugin API!

To read a theme value within a plugin, you can use the theme function available inside the plugin() function:

plugin(function ({ addbase, theme }) {
  const colorThemes = theme('multiTheme')
  addBase({
    // ...
  })
})

šŸ† Your challenge šŸ†

In the Tailwind Play belowā€¦

  1. Move the color themes definition into a custom key inside the Tailwind configā€™s theme.

  2. Update the plugin code to read the color theme values from the config file instead.


āœŒļø Good luck!

Start challenge