Emotion 완벽 가이드 | CSS-in-JS·성능·Styled·CSS Prop·실전 활용
이 글의 핵심
Emotion으로 고성능 CSS-in-JS를 구현하는 완벽 가이드입니다. Styled, CSS Prop, Theming, SSR, TypeScript까지 실전 예제로 정리했습니다.
실무 경험 공유: styled-components에서 Emotion으로 전환하면서, 번들 크기가 20% 감소하고 성능이 향상된 경험을 공유합니다.
들어가며: “CSS-in-JS가 느려요”
실무 문제 시나리오
시나리오 1: styled-components가 느려요
런타임 오버헤드가 있습니다. Emotion은 더 빠릅니다.
시나리오 2: 번들 크기가 커요
styled-components는 14KB입니다. Emotion은 7KB입니다.
시나리오 3: 더 유연한 API가 필요해요
styled만으로는 제한적입니다. Emotion은 css prop도 제공합니다.
1. Emotion이란?
핵심 특징
Emotion은 고성능 CSS-in-JS 라이브러리입니다.
주요 장점:
- 빠름: 최적화된 성능
- 작은 크기: 7KB
- 유연함: Styled + CSS Prop
- TypeScript: 완벽한 지원
- SSR: 서버 사이드 렌더링
2. 설치 및 기본 사용
설치
npm install @emotion/react @emotion/styled
Styled API
import styled from '@emotion/styled';
const Button = styled.button`
background: #3498db;
color: white;
padding: 0.5rem 1rem;
border: none;
border-radius: 4px;
cursor: pointer;
&:hover {
opacity: 0.8;
}
`;
export default function App() {
return <Button>Click me</Button>;
}
3. CSS Prop
설정 (Vite)
// vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [
react({
jsxImportSource: '@emotion/react',
}),
],
});
사용
/** @jsxImportSource @emotion/react */
import { css } from '@emotion/react';
const buttonStyle = css`
background: #3498db;
color: white;
padding: 0.5rem 1rem;
border: none;
border-radius: 4px;
cursor: pointer;
&:hover {
opacity: 0.8;
}
`;
export default function App() {
return <button css={buttonStyle}>Click me</button>;
}
4. Props 기반 스타일
import styled from '@emotion/styled';
interface ButtonProps {
variant?: 'primary' | 'secondary';
size?: 'small' | 'large';
}
const Button = styled.button<ButtonProps>`
background: ${(props) => (props.variant === 'primary' ? '#3498db' : '#2ecc71')};
color: white;
padding: ${(props) => (props.size === 'small' ? '0.25rem 0.5rem' : '0.5rem 1rem')};
border: none;
border-radius: 4px;
cursor: pointer;
`;
// 사용
<Button variant="primary" size="small">Small Primary</Button>
5. Theming
import { ThemeProvider } from '@emotion/react';
const theme = {
colors: {
primary: '#3498db',
secondary: '#2ecc71',
text: '#333',
background: '#fff',
},
spacing: {
sm: '0.5rem',
md: '1rem',
lg: '2rem',
},
};
const Button = styled.button`
background: ${(props) => props.theme.colors.primary};
color: white;
padding: ${(props) => props.theme.spacing.md};
`;
export default function App() {
return (
<ThemeProvider theme={theme}>
<Button>Themed Button</Button>
</ThemeProvider>
);
}
6. TypeScript 타입
import '@emotion/react';
declare module '@emotion/react' {
export interface Theme {
colors: {
primary: string;
secondary: string;
text: string;
background: string;
};
spacing: {
sm: string;
md: string;
lg: string;
};
}
}
7. Global Styles
import { Global, css } from '@emotion/react';
const globalStyles = css`
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: Arial, sans-serif;
line-height: 1.6;
}
`;
export default function App() {
return (
<>
<Global styles={globalStyles} />
{/* 나머지 컴포넌트 */}
</>
);
}
8. Composition
import { css } from '@emotion/react';
const baseStyle = css`
padding: 0.5rem 1rem;
border-radius: 4px;
`;
const primaryStyle = css`
${baseStyle}
background: #3498db;
color: white;
`;
const secondaryStyle = css`
${baseStyle}
background: #2ecc71;
color: white;
`;
// 사용
<button css={primaryStyle}>Primary</button>
<button css={secondaryStyle}>Secondary</button>
9. SSR (Next.js)
_document.tsx
import Document, { Html, Head, Main, NextScript, DocumentContext } from 'next/document';
import { CacheProvider } from '@emotion/react';
import createEmotionServer from '@emotion/server/create-instance';
import createCache from '@emotion/cache';
function createEmotionCache() {
return createCache({ key: 'css' });
}
export default class MyDocument extends Document {
static async getInitialProps(ctx: DocumentContext) {
const originalRenderPage = ctx.renderPage;
const cache = createEmotionCache();
const { extractCriticalToChunks } = createEmotionServer(cache);
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: (App: any) => (props) => (
<CacheProvider value={cache}>
<App {...props} />
</CacheProvider>
),
});
const initialProps = await Document.getInitialProps(ctx);
const emotionStyles = extractCriticalToChunks(initialProps.html);
const emotionStyleTags = emotionStyles.styles.map((style) => (
<style
data-emotion={`${style.key} ${style.ids.join(' ')}`}
key={style.key}
dangerouslySetInnerHTML={{ __html: style.css }}
/>
));
return {
...initialProps,
styles: [...React.Children.toArray(initialProps.styles), ...emotionStyleTags],
};
}
render() {
return (
<Html>
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
10. 실전 예제: 버튼 시스템
import styled from '@emotion/styled';
import { css } from '@emotion/react';
interface ButtonProps {
variant?: 'primary' | 'secondary' | 'danger';
size?: 'small' | 'medium' | 'large';
fullWidth?: boolean;
}
const Button = styled.button<ButtonProps>`
display: inline-flex;
align-items: center;
justify-content: center;
border: none;
border-radius: 4px;
cursor: pointer;
font-weight: 500;
transition: all 0.2s;
${(props) => {
const variants = {
primary: css`
background: #3498db;
color: white;
&:hover {
background: #2980b9;
}
`,
secondary: css`
background: #2ecc71;
color: white;
&:hover {
background: #27ae60;
}
`,
danger: css`
background: #e74c3c;
color: white;
&:hover {
background: #c0392b;
}
`,
};
return variants[props.variant || 'primary'];
}}
${(props) => {
const sizes = {
small: css`
padding: 0.25rem 0.5rem;
font-size: 0.875rem;
`,
medium: css`
padding: 0.5rem 1rem;
font-size: 1rem;
`,
large: css`
padding: 0.75rem 1.5rem;
font-size: 1.125rem;
`,
};
return sizes[props.size || 'medium'];
}}
${(props) =>
props.fullWidth &&
css`
width: 100%;
`}
&:disabled {
opacity: 0.5;
cursor: not-allowed;
}
`;
// 사용
<Button variant="primary" size="small">Small Primary</Button>
<Button variant="secondary">Medium Secondary</Button>
<Button variant="danger" size="large" fullWidth>Large Danger Full Width</Button>
정리 및 체크리스트
핵심 요약
- Emotion: 고성능 CSS-in-JS
- Styled + CSS Prop: 유연한 API
- 빠름: 최적화된 성능
- 작은 크기: 7KB
- TypeScript: 완벽한 지원
- SSR: 서버 사이드 렌더링
구현 체크리스트
- Emotion 설치
- Styled API 사용
- CSS Prop 활용
- Props 기반 스타일
- Theming 구현
- Global Styles
- SSR 설정
- TypeScript 타입
같이 보면 좋은 글
- styled-components 완벽 가이드
- React 완벽 가이드
- CSS-in-JS 가이드
이 글에서 다루는 키워드
Emotion, CSS-in-JS, React, Performance, Theming, TypeScript, Frontend
자주 묻는 질문 (FAQ)
Q. styled-components와 비교하면 어떤가요?
A. Emotion이 더 빠르고 번들 크기가 작습니다. API는 거의 동일합니다.
Q. CSS Prop이 뭔가요?
A. JSX에서 직접 css를 작성할 수 있는 기능입니다.
Q. MUI와 함께 사용할 수 있나요?
A. 네, MUI는 Emotion을 기본으로 사용합니다.
Q. 프로덕션에서 사용해도 되나요?
A. 네, MUI, Chakra UI 등이 Emotion을 사용하고 있습니다.