Next.js에서 Emotion과 TailwindCSS를 함께 사용하기 위한 설정

1. Next.js 설치
다음 명령을 사용해 Next.js의 최신 버전 + typescript를 설치한다.
npx create-next-app@latest --ts

아래 명령어로 설치 및 버전을 확인한다.
npx next -v

2. emotion 관련 라이브러리 설치
emotion 관련 라이브러리를 설치한다.
npm i @emotion/react @emotion/styled @emotion/css @emotion/server

3. tailwind, twin.macro 라이브러리 설치
tailwind, twin.macro 관련 라이브러리를 설치하고 devDependencies에 추가한다.
npm i twin.macro tailwindcss postcss@latest autoprefixer@latest @emotion/babel-plugin babel-plugin-macros --save-dev

config 파일 생성을 위해 다음 명령어를 사용한다.
tailwind.config.js를 사용하면 입맛에 맞게 사용자 지정 스타일을 사용할 수 있다.
npx tailwindcss init -p

/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
"./pages/**/*.{js,ts,jsx,tsx}",
"./components/**/*.{js,ts,jsx,tsx}",
],
theme: {
extend: {},
},
plugins: [],
};
styles/globals.css의 상단에 다음 코드를 추가한다. (HTML 태그 내에서 인라인으로 tailwind를 사용 가능하게 함)
@tailwind base;
@tailwind components;
@tailwind utilities;
4. .babelrc 생성
twin.macro의 사용이 가능하도록 plugin 설정을 해야 하므로 .babelrc 파일을 생성한다.

내부 설정은 다음과 같다.
{
"presets": ["next/babel"],
"plugins": ["babel-plugin-macros"]
}
5. 작동 테스트
emotion 및 emotion +tw(tailwind) 작동을 테스트한다.
아래 코드를 pages/index.tsx에 작성하고 npm run dev로 실행한다.
import type { NextPage } from "next"; import styles from "../styles/Home.module.css"; import styled from "@emotion/styled/macro"; import tw from "twin.macro"; const Input = tw.input` text-center border h-28 `; const MyDiv = styled.div` background: gold; font-size: 5rem; margin-top: 10px; `; const Home: NextPage = () => { return ( <div className={styles.container}> <main className={styles.main}> <h1 className={styles.title}> <Input placeholder="box" /> <MyDiv>Test Text</MyDiv> </h1> </main> </div> ); }; export default Home;
결과는 다음과 같다.

관련 링크
nextJS https://nextjs.org/
tailwindCSS https://tailwindcss.com/
emotion https://emotion.sh/docs/introduction
twin.macro https://github.com/ben-rogerson/twin.macro#readme