
React에서 자주 사용되는 Tailwind와 Styled-components를 같이 사용하는 방법을 알아보겠습니다.
npm install styled-components
npm install @types/styled-components
npm install tailwindcss
npm install postcss
npm install autoprefixer
Webpack 환경에서는 twin.macro 라이브러리를 vite환경에서는 vite-plugin-babel-macros를 설치해줍니다.
npm install vite-plugin-babel-macros
export default {
plugins: {
'postcss-import': {},
tailwindcss: {},
autoprefixer: {},
},
}
/** @type {import('tailwindcss').Config} */
export default {
content: [
"./src/**/*.{js,ts,jsx,tsx}",
],
theme: {
extend: {},
},
plugins: [],
}
@tailwind base;
@tailwind components;
@tailwind utilities;
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를 자주 사용하면서 속성을 암기하면 해결될 문제라고 생각되어 두개를 같이 지속적으로 사용할것 같습니다!