Tailwind component library - customize colors in implementing project

Viewed 242

I've built a component library with Tailwind and React. I'm building the dist files using Rollup. My tailwind.config.js file looks like this (notice the colors declaration):

const colors = require('tailwindcss/colors');

module.exports = {
  content: ['./src/**/*.{js,jsx,ts,tsx}'],
  theme: {
    extend: {
      colors: {
        primary: colors.green,
        secondary: colors.yellow,
        neutral: colors.slate,
      },
    },
  },
  plugins: [
    require('@tailwindcss/typography'),
    require('@tailwindcss/aspect-ratio'),
  ],
};

Now, in the implementing project, I want to customize those colors. For example, I want to set the primary color to colors.emerald.

How would I be able to pass the colors set in the parent config back to the component library? The building step is done when installing the package.

1 Answers

You could try implementing the colors using CSS variables and then set the variable values in a CSS file for your project's "theme".

tailwind.config.js

module.exports = {
  content: ['./src/**/*.{js,jsx,ts,tsx}'],
  theme: {
    extend: {
      colors: {
        primary: 'var(--theme-primary)',
        secondary: 'var(--theme-secondary)',
        ...
      },
    },
  },
  ...
}

theme.css

:root {
  --theme-primary: #fff;
  --theme-secondary: #ccc;
  ...
}

If you want to use the Tailwind color set, you could generate the CSS using JavaScript after including tailwindcss/colors.

Related