.env
COLOR_PRIMARY=0F4C80
COLOR_SECONDARY=F6F6F6
...
^v3.1.4
tailwind.config.js
설정을 하여 css 변수에 지정된 rgba 색상을 아래와 같이 값을 받아올 수 있다colors: {
primary: {
DEFAULT: 'rgb(var(--color-primary) / <alpha-value>)',
}
}
@layer components {
root: {
--color-primary: 255 255 255 30;
}
}
/utils/colors.ts
export function validHEX(hex: string) {
if (typeof hex !== 'string') {
return false
}
const reg = new RegExp(/^\#?[0-9a-fA-F]{6,8}$/)
return reg.test(hex)
}
//HEX → RGBA
export function HEX2RGBA(hex: string): Rgba {
if (!validHEX(hex)) {
throw new Error(`'${hex}' is not valid hex format!`)
}
let temp = hex.replace('#', '')
let len = temp.length / 2
let rgba: string[] = []
for (let i = 0; i < len; i++) {
let hTarget = temp.substring(i * 2, (i + 1) * 2)
//alpha value(0~1)
if (i === 3) {
rgba.push(String(parseInt(hTarget, 16) / 255))
} else {
//r,g,b value (0~255)
rgba.push(String(parseInt(hTarget, 16)))
}
}
return rgba as Rgba
}
export const setColorShades = (hex: string, theme: ColorTheme) => {
const rgb = HEX2RGBA(hex)
switch (theme) {
case ColorTheme.Primary:
document
.documentElement
.style
.setProperty('--color-primary', rgb.join(' '))
case ColorTheme.Secondary:
document
.documentElement
.style
.setProperty('--color-secondary', rgb.join(' '))
}
}
_app.tsx
import { setColorShades } from 'src/utils/colors'
...
useEffect(() => {
try {
setColorShades(COLOR_PRIMARY, ColorTheme.Primary)
} catch (e) {
console.warn(e)
}
}, [])
...