
tailwind css로 디자인을 구현한 코드에서 storybook을 사용해 ui 컴포넌트화를 진행하던 중, 적용한 디자인이 화면에 제대로 반영되지 않는 문제가 발생하였다.
// tailwind.config.js
module.exports = {
purge: ["./src/**/*.{js,jsx,ts,tsx}", "./public/index.html"],
darkMode: false,
theme: {
extend: {
colors: {
main: "#A860F6",
sub: "#D4B7F4",
bg: "#F8F6EE",
black: "#191D26",
gray: "#625D5D",
white: "#F8FAFF",
zinc300: "#D1D5DB",
zinc200: "#E5E7EB",
gray700: "#374151",
yellow400: "#facc15",
yellow300: "#fde047",
green500: "#10B981",
green400: "#34D399",
zinc100: "#F4F5F7",
},
},
},
사용할 스타일을 위와 같이 템플릿 리터럴로 지정하여
// Button.tsx
import React, { FormEvent } from "react";
export interface ButtonProps {
label: string;
type?: "submit" | "button";
backgroundColor: string;
hoverColor: string;
textColor: string;
buttonSize: string;
textSize: string;
}
function Button({
label,
type,
backgroundColor,
hoverColor,
textColor,
buttonSize,
textSize,
}: ButtonProps) {
const style = `bg-${backgroundColor} hover:bg-${hoverColor} text-${textSize} text-${textColor} ${buttonSize} py-2 px-4 rounded-md`;
return (
<button type={type} className={style}>
{label}
</button>
);
}
export default Button;
버튼 컴포넌트 파일을 작성한 뒤
// ButtonArgs.ts
export const authButtonArgs = {
backgroundColor: "zinc300",
hoverColor: "zinc200",
textColor: "gray700",
buttonSize: "w-64 h-12",
textSize: "base",
};
export const kakaoButtonArgs = {
backgroundColor: "yellow400",
hoverColor: "yellow300",
textColor: "gray",
buttonSize: "w-16 h-16",
textSize: "base",
};
export const naverButtonArgs = {
backgroundColor: "green500",
hoverColor: "green400",
textColor: "gray",
buttonSize: "w-16 h-16",
textSize: "base",
};
export const googleButtonArgs = {
backgroundColor: "white",
hoverColor: "zinc100",
textColor: "gray",
buttonSize: "w-16 h-16",
textSize: "base",
};
ButtonArgs.ts 파일을 따로 만들어 버튼 컴포넌트 스타일을 각각 지정해주었다.
이후 링크 내용에 따라 storybook과 tailwind를 연동해서 사용할 수 있도록 설정하였는데 화면에서 버튼 컬러가 적용이 되지 않았다...😩

클래스에 변수가 잘 지정되어 있는 것이 찍히는데.. 화면에는 나타나지 않는 것인지 !!!
구글링 그리고 팀원들과의 논의를 통해서 이유를 파악할 수 있었다.
tailwind css는 zero-runtime 라이브러리이다.
따라서 위와 같이 변수식으로 스타일을 작성하면 tailwind css가 빌드타임에 클래스를 생성하지 못한다고 한다.
이처럼 tailwind는 동적 할당을 인식하지 못하기 때문에, 코드가 컴파일링되는 시점에서 사용되지 않는 CSS는 제거해 버린다고 한다. 따라서 변수로 지정했던 클래스가 제거되어 적용되지 않았던 것...!
즉, tailwind css는 동적으로 생성된 클래스는 인식하지 않기 때문에, 템플릿 리터럴을 사용해서 동적으로 할당하는 방식이 문제가 된 것이다.
tailwind css를 그대로 사용하면서 이러한 현상을 해결하기 위해서는 객체로 디자인코드를 새로 작성하거나, 혹은 tailwind.config 내장 기능인 safeList 프로퍼티에 할당하는 방법으로 해결이 가능하다.
그러나 이는 스토리북 사용과 컴포넌트 재사용성에 불리하므로 진행 중인 프로젝트에 부적합한 해결법이라는 판단이 들었다.
따라서 근본적인 해결법이라고는 볼 수 없으나 컴포넌트화한 ui 코드들을 styled-components로 마이그레이션하기로 결정했다...
tailwind css와 styled-components를 동시 사용하는 코드가 되어 통일감이 없어 보일 수 있어서 이후 zero-runtime css 도구인 Vanila Extract로 마이그레이션해볼 생각이다.
참고링크
https://velog.io/@arthur/Tailwind-CSS-에서-동적으로-클래스-할당하기
https://velog.io/@mindev/Storybook-Tailwindcss에서-color-theme-적용안되는-현상