Skip to content

설치 ​

요구 사항 ​

  • React 16.14 이상 — 자동 JSX runtime(react/jsx-runtime)이 16.14에서 들어왔어요
  • @emotion/react 11.x
  • @emotion/css 11.x

설치하기 ​

sh
pnpm add emotion-variants @emotion/react @emotion/css
sh
npm install emotion-variants @emotion/react @emotion/css
sh
yarn add emotion-variants @emotion/react @emotion/css

Emotion 패키지 두 개는 모두 peer dependency라서 emotion-variants와 함께 꼭 설치해야 해요. @emotion/react는 css prop에 넘길 스타일을 직렬화하고, @emotion/css는 className()과 classNames를 담당해요. @emotion/css는 조건 없이 import되기 때문에, css prop만 쓴다고 해도 설치는 필요해요.

css prop 활성화 ​

emotion-variants가 반환하는 값은 Emotion의 css prop에 그대로 넘기는 형태예요. 그래서 프로젝트에 css prop이 활성화돼 있어야 동작해요. 가장 간단한 방법은 자동 JSX runtime이 Emotion을 가리키게 하는 거예요.

json
// tsconfig.json
{
  "compilerOptions": {
    "jsx": "react-jsx",
    "jsxImportSource": "@emotion/react"
  }
}

두 옵션이 모두 필요해요. "jsx": "react"에서는 jsxImportSource가 아무 효과가 없어요. 그건 classic transform이라 React.createElement를 호출하고 import source를 보지 않아요.

프로젝트 전체 설정을 바꾸기 어렵다면 파일 단위로도 할 수 있어요.

tsx
/** @jsxImportSource @emotion/react */

이 pragma도 자동 runtime이 전제라서, 파일의 가장 첫 줄에 있어야 하고 그 파일이 react-jsx로 컴파일돼야 해요. React 16.14보다 낮은 버전이라면 Emotion의 Babel 플러그인과 classic transform을 쓰세요.

다른 설정 방법(Next.js, Vite 등)은 Emotion 공식 설치 가이드를 참고해 주세요.

동작 확인 ​

작은 컴포넌트를 하나 만들어 렌더링해 보세요. button({ ... }) 안에서 TypeScript가 size를 자동완성해 주면 잘 설정된 거예요.

tsx
import { ev } from 'emotion-variants';

const button = ev({
  base: {
    padding: '8px 16px',
  },
  variants: {
    size: {
      sm: {
        fontSize: 12,
      },
      lg: {
        fontSize: 16,
      },
    },
  },
});

type ButtonProps = NonNullable<Parameters<typeof button>[0]> & {
  children: React.ReactNode;
};

export function Button({ size, children }: ButtonProps) {
  return <button css={button({ size })}>{children}</button>;
}

다음: 시작하기.

MIT 라이선스에 따라 배포돼요.