React + Vite + Tailwind + Styled-compnents 사용하기

쭌로그·2024년 11월 4일

React

목록 보기
1/2
post-thumbnail

React에서 자주 사용되는 Tailwind와 Styled-components를 같이 사용하는 방법을 알아보겠습니다.

왜 같이 사용할까?

  • tailwind사용시 class 길이가 너무 길어저 가독성이 떨어지게됩니다.
  • 동일한 class를 반복적으로 사용해야하는 불편함이 존재합니다.
  • tailwind와 Styled-component를 통한 props 바인딩으로 간결한 코드 작성이 가능합니다.

1. Styled-component 설치

npm install styled-components
npm install @types/styled-components

2. Tailwind 설치

npm install tailwindcss
npm install postcss
npm install autoprefixer

3. twin.macro 설치

Webpack 환경에서는 twin.macro 라이브러리를 vite환경에서는 vite-plugin-babel-macros를 설치해줍니다.

npm install vite-plugin-babel-macros

설정파일 셋팅

1. postcss.config.js 설정

export default {
  plugins: {
    'postcss-import': {},
    tailwindcss: {},
    autoprefixer: {},
  },
}

2. tailwind.config.js 설정

/** @type {import('tailwindcss').Config} */
export default {
  content: [
    "./src/**/*.{js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}

3. index.css 설정

@tailwind base;
@tailwind components;
@tailwind utilities;

4. vite.config.js 설정

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react-swc'
import macrosPlugin from 'vite-plugin-babel-macros';
...
export default defineConfig({
  plugins: [react(), macrosPlugin()],
  resolve: {
    ...
    ],
  },
})

사용법

import styled from 'styled-components';
import tw from 'twin.macro';
import MailIcon from '@/assets/email.png'
import Button from '../components/Button';
const Container = styled.div`
  ${tw`
    absolute
    left-1/2
    top-1/2
    w-[800px]
    h-[400px]
    flex
    flex-col
    gap-4
    bg-white
    rounded-lg
    p-4
    text-center
    box-border
  `}
  ${
  `
    transform: translateY(-50%) translateX(-50%);
  `}
`;

const Title = styled.div`
  ${tw`
    text-center
    font-bold
    text-3xl
  `}
`

const Logo = styled.div`
  background-image : url(${MailIcon});
  background-repeat: no-repeat;
  background-size: cover;
  margin: 0 auto;
  width: 100px;
  height: 100px;
`
const MainText = styled.div`
  font-size: 2rem;
  font-weight: bold;
  flex-grow: 1;
`

export default function HomePage() {
  return (
    <Container>
      <Logo />
      <Title>Develetter</Title>
      <MainText>나의 커리어 정보를 손쉽게 받아보세요!</MainText>
      <Button text={"클릭"} onClick={() => {}} />
      <div>
        깃허브, 이메일, 블로그
      </div>
      <div>본 사이트는 유저의 정보를 수집하고 있습니다. 사용시 주의해주세요.</div>
    </Container>
  )
}

위의 코드는 tailwind와 styled-component의 CSS 속성을 동시에 사용하는 코드입니다. tailwind를 사용할 때에는 tw.xxx를 CSS를 사용하고 싶을 때에는 styped-components를 사용할 때처럼 그대로 사용하면 됩니다.

정리

Tailwind와 Styled-component를 같이 사용하면 다독성과 유지보수성 두마리의 토끼를 모두 잡는듯한 느낌을 받았습니다. 그러나 Tailwind의 다양한 속성값을 hint로 확인할 수 없어 class에 먼저 바인딩 한 후 복사하여 styled-component에 적용하는 번거로움 또한 존재했습니다. 그러나 Tailwind를 자주 사용하면서 속성을 암기하면 해결될 문제라고 생각되어 두개를 같이 지속적으로 사용할것 같습니다!

profile
매일 발전하는 프론트엔드 개발자

0개의 댓글