tailwindcss의 동적할당

Hwang Tae Young·2023년 1월 10일
0

하하하하 저번주에 완성한다는 나의 포켓몬 토이프로젝트는 이번 주 까지 밀려버렸다,,,,,, 그리고 오늘은 디자인을 완성 하려했지만 tailwindcss에서 막혀버린상황! 그리고 해결책은 보이지만 찜찜한 그런 느낌이다!

🚀 오늘의 반쪽자리 트러블 슈팅

내가 하고자 했던 것은 pokemonTypeColor를

export const pokemonTypeColor: Record<string, string> = {
  normal: "#ADA594",
  fighting: "#C03028",
  flying: "#5D73D4",
  poison: "#6B246E",
  ground: "#d97746",
  rock: "#9E863D",
  bug: "#888C0E",
  ghost: "#695582",
  steel: "#E08EE0",
  fire: "#e25304",
  water: "#0267C2",
  grass: "#389A02",
  electric: "#EDA900",
  psychic: "#DC3165",
  ice: "#6dd3f5",
  dragon: "#4E3BA4",
  dark: "#3C2D23",
  fairy: "#E08EE0",
  unknown: "#008080",
  shadow: "#3C2D23",
};

아래의 코드에 적용시켜 동적인 클래스 지정을 통해 색을 입히는 것이었다!

import pokemonTypeColor from "../../../static/pokemonTypeColor";

ㅡㅡㅡㅡ

  const { data: type, isLoading: isTypeLoading } = useGetPokemonInfoQuery({
    id,
    key: "type",
  });
  const typeColor = pokemonTypeColor[type?.[0];
return (
<p className="shadow-md inline-block rounded-full leading-7 pr-3">
  <span
    className={`
      bg-[${typeColor]]
    text-white px-3 rounded-full mr-2 inline-block`}
  >
    {id}
  </span>
  {pokemonName}
</p>
)


위에 이미지처럼 클래스명은 할당 되지만, 적용이 되지 않았는 문제가 생겼고, 열심히 구글링을 해보니 tailwindcss는 컴파일 단계에서 사용되지 않는 클래스명은, stylesheet에서 지워 버린다고한다,,,

실제로 공식문서에도 동적으로 할당하는 것은 좋지 않다라고 써있다!
그리고, 해결방법으로는 두가지 방법을 제시해준다.

1. Safelisting classes

  • config에서 사용하지 않아도, 지워지지 않게끔 설정하는 것이다.
    하지만 이 방법은 내가 사용할 변수가 많아서 패스,,,, 너무많다,,,!
module.exports = {
  content: [
    './pages/**/*.{html,js}',
    './components/**/*.{html,js}',
  ],
  safelist: [
    'text-2xl',
    'text-3xl',
    {
      pattern: /bg-(red|green|blue)-(100|200|300)/,
    },
  ],
  // ...
}

2. Always use complete class names

  • 두번째 방법은 변수 설정등을 할때 항상 완성된 클래스명을 사용하는 것이다! 아래와 같이 부분적으로 끊어지는게 아닌, 완성된 클래스명으로 만드는 것이고 나는 이방법을 채택했는데 또 문제가 생겼다.
<div class="{{ error ? 'text-red-600' : 'text-green-600' }}"></div>

문제상황 😡

  • 완성된 클래스명을 넣어줄때, 아래와 같이 넣으니 동작하지 않았다. 아마 컴파일할때 사용하지 않았다고 tailwind가 판단한 것 같다. 그래서 참고한 블로그를 보고 pokemonTypeColor을 수정했다.
  const { data: type, isLoading: isTypeLoading } = useGetPokemonInfoQuery({
    id,
    key: "type",
  });
  //const typeColor = pokemonTypeColor[type?.[0];
  //이부분을 아래와 같이 바꿈
  const typeColor = type?.[0]&&`bg-[pokemonTypeColor[type?.[0]]`;
return (
<p className="shadow-md inline-block rounded-full leading-7 pr-3">
  <span
    className={`
    ${typeColor}
    text-white px-3 rounded-full mr-2 inline-block`}
  >
    {id}
  </span>
  {pokemonName}
</p>
)

해결?🤔

변경된 pokemonTypeColor

const pokemonTypeColor: Record<string, string> = {
  normal: "bg-[#ADA594]",

  fighting: "bg-[#C03028]",

  flying: "bg-[#5D73D4]",

  poison: "bg-[#6B246E]",

  ground: "bg-[#d97746]",

  rock: "bg-[#9E863D]",

  bug: "bg-[#888C0E]",

  ghost: "bg-[#695582]",

  steel: "bg-[#E08EE0]",

  fire: "bg-[#e25304]",

  water: "bg-[#0267C2]",

  grass: "bg-[#389A02]",

  electric: "bg-[#EDA900]",

  psychic: "bg-[#DC3165]",

  ice: "bg-[#6dd3f5]",

  dragon: "bg-[#4E3BA4]",

  dark: "bg-[#3C2D23]",

  fairy: "bg-[#E08EE0]",

  unknown: "bg-[#008080]",

  shadow: "bg-[#3C2D23]",
};

그리고 컴포넌트에서도 바꾸었다.

  const { data: type, isLoading: isTypeLoading } = useGetPokemonInfoQuery({
    id,
    key: "type",
  });
  //const typeColor = pokemonTypeColor[type?.[0];
  //이부분을 아래와 같이 바꿈
  //const typeColor = type?.[0]&&`bg-[pokemonTypeColor[type?.[0]]`;
  //아예 삭제
return (
<p className="shadow-md inline-block rounded-full leading-7 pr-3">
  <span
    className={`
    ${pokemonTypeColor[type?.[0] ?? "flying"]} //초기값을 넣어주어 일단 색이라도 나오게,,,
    text-white px-3 rounded-full mr-2 inline-block`}
  >
    {id}
  </span>
  {pokemonName}
</p>
)

이렇게 하니까 동작이 분명 되서 기분이 좋았는데, 갑자기 또 안된다 ㅋㅋㅋ 그래서 pokemonTypeColor 자체를 컴포넌트에 임포트해오는게 아닌, 바로 넣어버려서 동작 시키니까 또 동작한다🥲 제일 지금 혼란스럽고 당화스러운건, 현재 저 동적으로 동작하게끔 만드는게, 단 2가지 컴포넌트에 적용시켜야 하는데 둘 다 임포트 해왔을 때는 동작하지 않지만, 내 프로젝트에 있는 아무 컴포넌트에

const pokemonTypeColor: Record<string, string> = {
  normal: "bg-[#ADA594]",

  fighting: "bg-[#C03028]",

  flying: "bg-[#5D73D4]",

  poison: "bg-[#6B246E]",

  ground: "bg-[#d97746]",

  rock: "bg-[#9E863D]",

  bug: "bg-[#888C0E]",

  ghost: "bg-[#695582]",

  steel: "bg-[#E08EE0]",

  fire: "bg-[#e25304]",

  water: "bg-[#0267C2]",

  grass: "bg-[#389A02]",

  electric: "bg-[#EDA900]",

  psychic: "bg-[#DC3165]",

  ice: "bg-[#6dd3f5]",

  dragon: "bg-[#4E3BA4]",

  dark: "bg-[#3C2D23]",

  fairy: "bg-[#E08EE0]",

  unknown: "bg-[#008080]",

  shadow: "bg-[#3C2D23]",
};

이 코드를 넣어놓기만해도 동작한다. 왜 그럴까,,,,? 대체 나한테 왜이럴까 ㅠㅠㅠㅠㅠ
현재 완전한 해결책이라고는 애매하다,,, 그리고 정 안되면 인라인스타일로 넣는 방향으로 해야겠지만 tailwindcss로 시작한것, 마무리도 tailwindcss로 완성하고 싶은데 어떻게 해야할까!

profile
더 나은 개발자가 되기 위해...☆

0개의 댓글