React

Tailwindcss와 Css-in-js 함께 사용하기 (twin.macro)

citron031 2023. 5. 29. 23:22

tailwindcss는 분명 장점이 있는 CSS 작성법이다.

다만, 어떤 경우에는 tailwindcss만 사용하는 것이 생산성을 떨어트릴 수도 있다.

     🍋 예를 들면, 스타일이 많이 적용될 경우 인라인으로 클래스명이 너무나도 길어질 수 있다. (코드 가독성 저하)

이런 경우, 기존에 사용했던 styled-component나 emotion과 같은 css-in-js 라이브러리가 그리워지는데 이 둘을 모두 함께 사용할 수 있게 도와주는 오픈소스 라이브러리가 있다.

🍵 twin.macro (with. emotion)

twin.macro의 깃허브 리드미를 살펴보면, 친절하게 각 환경에서 세팅하는 방법을 알려주고 있다.

그중에서 난 CRA 환경에서 emotion을 사용하여 개발 환경을 구축해보았다.

styled-component가 아니라 emotion을 사용한 이유는 typescript 환경에서 styled-component는 추가로 타입 라이브러리를 설치해야하는 번거로움이 있었기 때문이다.

🍙 또한, emotion이 next.js에서 설정이 더 편리하다.

 

https://github.com/ben-rogerson/twin.macro#get-started

 

GitHub - ben-rogerson/twin.macro: 🦹‍♂️ Twin blends the magic of Tailwind with the flexibility of css-in-js (emotion, st

🦹‍♂️ Twin blends the magic of Tailwind with the flexibility of css-in-js (emotion, styled-components, stitches and goober) at build time. - GitHub - ben-rogerson/twin.macro: 🦹‍♂️ Twin blends the ma...

github.com

 

이제 CRA 프로젝트에서 필요한 라이브러리를 설치하자.

npm install twin.macro tailwindcss @emotion/react @emotion/styled

그리고 babel-plugin-macros.config.js에 설정을 해준다.

나는 css-in-js 라이브러리로 emotion을 사용한다.

module.exports = {
  twin: {
    preset: 'emotion',
  },
}

이제 twin.macro를 사용할 수 있다.

사용법은 다음과 같다.

 

🍌 기존의 tailwindcss를 사용하는 것 처럼, 인라인으로 사용할 수 있다.

/** @jsxImportSource @emotion/react */
import tw from 'twin.macro'

const Input = () => <input tw="bg-black text-amber-400" />

export default function StylePage() {
  return (
    <div>
      <h1>Hi</h1>
      <Input />
    </div>
  )
}

 

🥪 emotion을 사용하는 것 처럼, 컴포넌트 방식을 사용할 수도 있다.

/** @jsxImportSource @emotion/react */
import tw from 'twin.macro'

const Button = tw.button`
  border-2 p-4 m-4 hover:bg-yellow-300
`

export default function StylePage() {
  return (
    <div>
      <h1>Hi</h1>
      <Button onClick={() => window.alert("!!@@")}>클릭!!</Button>
    </div>
  )
}

 

 

상단에 /** @jsxImportSource @emotion/react */ 를 입력해주어야 twin.macro를 인식할 수 있다.