Last active
March 23, 2021 20:42
-
-
Save dmwyatt/47366007d32cf252044864e367b2dc9c to your computer and use it in GitHub Desktop.
Extract color value from tailwind theme.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import resolveConfig from "tailwindcss/resolveConfig"; | |
// Update next import to the location of your tailwind config. If you're using CRA | |
// and your `tailwind.config.js` is outside of `src`, you might have to do | |
// Shenanigans™ to import it. (You can use craco and https://stackoverflow.com/a/60353355/23972) | |
import tailwindConfig from "../../tailwind.config"; | |
const THEME = resolveConfig(tailwindConfig).theme; | |
/** | |
* Given a color-containing Tailwind class, look up the hex color value. | |
*/ | |
export function getColorValue(classname) { | |
const parts = classname.split("-"); | |
// Assume the first part of the classname is the tailwind variant. | |
const colorParts = parts.slice(1); | |
// ...but also just try all the parts of the classname. | |
const value = | |
nestedGet(THEME.colors, colorParts) || nestedGet(THEME.colors, parts); | |
if (!value) { | |
throw new Error(`Cannot extract color name from: "${classname}"`); | |
} | |
return value; | |
} | |
/** | |
* Given list of stings, access nested properties in object. | |
* | |
* @param {Object<string, *>} object | |
* @param {Array<string>} accessors | |
* @returns {*} | |
*/ | |
export function nestedGet(object, accessors) { | |
return accessors.reduce((acc, prop) => { | |
return acc?.[prop]; | |
}, object); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment