리액트 프로젝트를 시작하기 앞서 디자인을 편하게 하기 위해 CSS 프레임워크를 사용하기로 했다. 그래서 가장 많이 사용하는 tailwind를 선택해서 개발해 보기로 했다.
1. Tailwind
tailwind는 아래처럼 classname(react의 경우 class가 아닌 className으로 해줘야 한다.)에 스타일을 입력하면 바로 css가 적용되는 녀석이다.
<div className="w-96 bg-white shadow rounded">
처음에는 tailwind만 적용해서 코드를 짜보려고 했는데 하다보니 classname 길이가 엄청 길어져서 가독성이 많이 떨어졌다. 그래서 찾아보니 리액트는 보통 styled-componets를 이용해서 주로 css를 짠다고 하는데... 지금이라도 바꿔야 하나 생각했지만, 조금 더 찾아보니 twin macro를 사용하면 Tailwind와 styled-componets를 같이 조합해서 사용할 수 있다고 한다.
이렇게 사용하게 된다면 길게 늘어진 클래스 이름을 줄이고 styled-componets로 css를 따로 분리시켜 코드의 가독성을 높일 수 있고 조금 더 효율적으로 작성할 수 있다.
그래서 이 둘을 사용하기 위한 설치 과정을 적어보겠다.
필자의 경우 이전에 프로젝트를 위해 [vite + react + typescript + swc] 환경에서 설치를 마저 진행하겠다.
2. Tailwind 설치
터미널을 열어 react가 설치되어있는 프로젝트로 이동해준다음 tailwind를 설치할 건데 여기서 postcss 플러그인(css 동작 자동화를 위한 플러그인)으로 설치해 볼 것이다.
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
설치를 하고 나면 postcss.config.js 와 tailwind.config.js라는 파일이 생성되었을 것이다.
다음으로는 styled-componets를 설치해 보겠다.
npm install styled-components@latest
그다음 twin.macro를 설치해 준다.
npm install twin.macro
필자는 vite로 프로젝트를 생성했기 때문에 babel-plugin-macros를 설치해 twin.macro의 기능 중 tw 매크로 기능을 사용할 수 있도록 하였다.
npm install vite-plugin-babel-macros
3. 설정 마무리
설치는 이제 다 끝났다. 모두 설치가 완료되었다면 tailwind와 styled-components를 사용하기 위해 프로젝트 파일들을 수정해야 한다.
vite.config.ts 파일을 열어 vite-plugin-babel-macros를 추가해 준다.
vite.config.ts
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react-swc'
//플러그인 추가
import macrosPlugin from 'vite-plugin-babel-macros'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
react(),
macrosPlugin(), //플러그인 추가
],
})
다음으로 src/index.css 파일을 열어 tailwind At-Rule을 추가해 준다.
index.css
/*index.css*/
@tailwind base;
@tailwind components;
@tailwind utilities;
4. 사용 방법
4-1. tailwind 사용(단독사용)
다음으로 tailwind.config.js과 postcss.config.js 파일을 수정해 준다.먼저 tailwind.config.js 파일에서 content 부분만 아래처럼 수정해 주면 된다.
tailwind.config.js
/** @type {import('tailwindcss').Config} */
export default {
content: [
"./src/**/*.{js,ts,jsx,tsx}",
],
theme: {
extend: {},
},
plugins: [],
}
그리고 postcss.config.js 파일에서 아래처럼 코드를 수정해 준다.
postcss.config.js
export default {
plugins: {
'postcss-import': {},
tailwindcss: {},
autoprefixer: {},
},
}
이제 tailwind를 사용할 수 있게 되었다. 먼저 tailwind를 styled-components 없이 사용하게 되면 아래처럼 사용하여야 한다.
예시를 위해 App.tsx 파일에서 코드를 수정해 보겠다.
App.tsx
import './App.css'
function App() {
return (
<>
<div className='m-10 text-3xl font-bold underline text-blue-500'>
Hello world!
</div>
</>
)
}
export default App
4-2. tailwind + styled-components 사용
저 className에 style 코드를 입력해 주면 되는데 만약 적용해야 하는 스타일이 많거나 코드가 많아지면 복잡해져 코드를 읽기 많이 불편해질 것이다. 이제 twin macro를 사용해 보도록 하겠다. styled-components와 twin.macro를 import 해주고
아래 코드처럼 컴포넌트를 만들어 준다. 이렇게 되면 더 이상 classname에 스타일을 작성하지 않고 따로 빼서 코드의 가독성을 높일 수 있게 되었다.
import './App.css'
import styled from 'styled-components';
import tw from 'twin.macro';
function App() {
return (
<>
<Container>
Hello world!
</Container>
</>
)
}
const Container = styled.div`
${tw`m-10 text-3xl font-bold underline text-red-500`}
`;
export default App
추가적으로 vscode를 사용한다면 아래의 확장프로그램(Tailwind CSS IntelliSense)을 설치하면 조금 더 편하게 개발할 수 있다.
문제는 styled-components에는 적용이 안 되는 것 같다...(그런데 해결 방법을 찾았다!)
Ctrl + Shift + P를 눌러 settings.json을 열어 아래의 값을 입력하고 저장해 주면 된다.
"tailwindCSS.experimental.classRegex": [
"tw`([^`]*)", // tw`...`
"tw=\"([^\"]*)", // <div tw="..." />
"tw={\"([^\"}]*)", // <div tw={"..."} />
"tw\\.\\w+`([^`]*)", // tw.xxx`...`
"tw\\(.*?\\)`([^`]*)" // tw(Component)`...`
],
"tailwindCSS.includeLanguages": {
"typescript": "javascript",
"typescriptreact": "javascript"
}
출처 : https://github.com/ben-rogerson/twin.macro/discussions/227
Tailwind CSS IntelliSense and Twin · ben-rogerson twin.macro · Discussion #227
Good news, Brad has just pushed a new release that includes an experimental custom regex feature. Installation Install the extension in VSCode: From your command palette select: "Preferences: Open ...
github.com
이제 모든 설정이 끝났고 본격적으로 개발을 시작해 보도록 하겠다.
'프론트엔드 개발 > React' 카테고리의 다른 글
[React] 카카오 지도 API 연동하기 (TS + Vite) (2) | 2024.09.02 |
---|---|
[React] D-Day 계산하기 (typescript) (0) | 2024.08.28 |
[React] 갤러리 화면에서 이미지 모달창 기능 구현하기(Typescript) (0) | 2024.08.09 |
[React] 간단한 갤러리 화면 구현하기(Typescript) (0) | 2024.08.08 |
[React] Vite + React 프로젝트 구성하기 (0) | 2024.07.16 |