Emotion css prop 해결하기

Sei Kim·2024년 10월 8일
0

개요

Emotion을 사용하면서 css를 prop으로 넘기고 있었는데 아래와 같은 문제가 발생하였습니다.

이로 인해서 정상적으로 CSS가 입혀지지 않아 컴포넌트가 깨져서 보였습니다.


CSS가 적용이 되지 않았다.

문제가 발생했던 예제 코드는 다음과 같습니다.

<Button
  styles={{ $size: 'medium', $variant: 'outline' }}
  onClick={handleOpenCreate}
  children={<span className={'font-extrabold'}>일정 등록</span>}
  className="py-2 mb-5"
/>
export interface ButtonProps extends ComponentPropsWithoutRef<'button'> {
  /**
   * Button 컴포넌트가 사용할 HTML 태그
   *
   * @default 'button'
   */
  tag?: ElementType;
  /** Button 스타일 옵션 */
  styles: ButtonStyling;
  /** Button 하위 컴포넌트 */
  children: React.ReactNode;
}

function Button({
  tag = 'button',
  styles,
  children,
  ...attributes
}: ButtonProps) {
  const Tag = tag;

  return (
    <Tag
      css={[
        getButtonStyling(),
        getSizeStyling(styles.$size),
        getVariantStyling(styles.$variant),
      ]}
      {...attributes}
    >
      {children}
    </Tag>
  );
}

export default Button;

해결법

해당 프로젝트는 vite, typescript, react, emotion 를 사용하고 있었고 관련 문제를 해결하기 위해 설정들을 수정하였습니다.

tsconfig.json

{
  "compilerOptions": {
    "target": "ES2020",
    "useDefineForClassFields": true,
    "lib": ["ES2020", "DOM", "DOM.Iterable"],
    "module": "ESNext",
    "skipLibCheck": true,
    "jsxImportSource": "@emotion/react", // 해당 부분 추가
    ...

"jsxImportSource": "@emotion/react" 옵션을 tsconfig.jsoncompilerOptions에 추가하였습니다.

vite.config.ts

export default defineConfig({
  plugins: [
    react({
      jsxImportSource: '@emotion/react', // 해당 부분 추가
    }),
    macrosPlugin(),
    ...

vite.config.tsplugins - reactjsxImportSource: '@emotion/react'을 추가하여 정상적으로 동작하도록 수정하였습니다.

이후 CSS를 확인해보면 정상적으로 적용된 것을 확인할 수 있습니다.

Ref

0개의 댓글