본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

Sass에서 Emotion으로 마이그레이션

원문 보기 위키 갱신

Sass에서 Emotion으로 마이그레이션 (Migrating from Sass to Emotion)

이 페이지는 특정 Sass 변수와 믹스인을 해당 Emotion 대응으로 마이그레이션하는 방법에 대한 편리한 참조/치트시트입니다.

출처: 문서

본문

Migrating from Sass to Emotion

이 페이지는 특정 Sass 변수와 믹스인을 해당 Emotion 대응으로 마이그레이션하는 방법에 대한 편리한 참조/치트시트입니다.

Variables

Sizes

전체 토큰 목록은 Sizing tokens을 참고하세요.

Performing math on size tokens

이 크기 토큰들이 숫자가 아닌 CSS 문자열을 반환한다는 점을 강조할 가치가 있습니다. 즉 $euiSize * 10 같은 것은 Sass에서보다 훨씬 더 많은 문법적 설탕이 필요합니다. 커스텀 크기를 계산해야 한다면 다음 세 가지 방법 중 하나를 사용할 수 있습니다:

  • euiTheme.base는 수학 연산을 수행할 수 있는 숫자(기본값 16)를 반환합니다. 예:
const width = ${useEuiTheme().euiTheme.base * 10}px; // '160px'
  • EUI는 전달된 문자열의 단위를 보존하는 mathWithUnits 유틸리티를 제공합니다. 사용 예:
import { mathWithUnits } from '@elastic/eui';

const SomeComponent = () => {
  const { euiTheme } = useEuiTheme();

  const width = mathWithUnits(euiTheme.size.base, (x) => x * 10); // Returns '160px'

  // 이 유틸은 여러 토큰도 받습니다. 예:
  const height = mathWithUnits([euiTheme.size.xl, euiTheme.size.xs], (x, y) => x + y); // Returns '44px'
}
  • 또는 CSS 내장 calc() 함수를 사용하는 것을 선호할 수도 있습니다. 예:
width: calc(${euiTheme.size.base} * 10);

Colors

전체 토큰 목록은 Color tokens을 참고하세요.

Color palettes

$euiColorPaletteBlind은 이제 커스터마이즈 가능한 팔레트 배열을 생성하는 함수입니다. 이전 Sass 버전 그대로 사용하려면 인수 없이 호출하면 됩니다:

import { euiColorPaletteBlind, euiPaletteColorBlindBehindText } from '@elastic/eui';

// 이 유틸들은 훅이나 react 컴포넌트 바깥에서 정적으로 호출할 수 있음을 참고하세요
const visColors = euiColorPaletteBlind();
const visBackgroundColors = euiPaletteColorBlindBehindText();

const SomeComponent = () => <div css={{ color: visColors[0], backgroundColor: visBackgroundColors[1] }} />

전체 인수 목록은 Color palettes를 참고하세요.

Typography

전체 토큰 목록은 Typography tokens을 참고하세요. 안타깝게도 폰트 크기는 더 이상 정적 토큰(static tokens)이 아니며, 함수/훅으로 계산해야 합니다. 아래 "Typography" 믹스인 섹션을 참고하세요.

Z-index levels

z-index 레벨에 대한 수학에 관한 간단한 참고: 테마에 잠재적으로 문자열 또는 숫자(CSS 속성의 기본 타입)로 입력되지만, 반환되는 토큰은 숫자이며 그대로(예: 덧셈) 수학 연산이 가능합니다.

Borders

전체 토큰 목록은 Border tokens을 참고하세요.

Animations

Form variables ⚠️

EUI에는 현재 $euiForm Sass 변수에 대한 마이그레이션 경로가 없습니다. 경로가 생길 때까지 이 변수들을 폐기하지 않을 것입니다.

Mixins

Typography

위에서 언급했듯이 $euiFontSize* 토큰은 더 이상 존재하지 않습니다. 대신 fontSize와 lineHeight를 객체 형식으로 모두 반환하는 유틸리티를 사용해야 합니다. 일반적으로 가능하다면 CSS로 폰트 크기를 직접 적용하는 대신 EuiText와 EuiTitle을 사용할 것을 강력히 권장합니다.

컴포넌트를 절대 사용할 수 없다면, 폰트 스타일링을 대체하기 위해 일반적으로 useEuiFontSize() 훅을 권장합니다:

import { useEuiFontSize } from '@elastic/eui';
import { css } from '@emotion/react';

const SomeComponent = () => {
  const cssStyles = [
    useEuiFontSize('l'),
    css`
      color: red;
    `,
  ];

  return <div css={cssStyles} />
}
import { useEuiFontSize } from '@elastic/eui';
import { css } from '@emotion/react';

const SomeComponent = () => {
  const euiThemeContext = useEuiTheme();
  const cssStyles = css`
    font-size: ${useEuiFontSize('l').fontSize};
    line-height: 1;
  `;

  return <div css={cssStyles} />
};

전체 className 유틸리티 목록과 문서는 Typography utilities를 참고하세요.

Responsive

EUI의 브레이크포인트 유틸리티는 일반적으로 Sass 능력을 넘어서도록 향상되었습니다. 이를 염두에 두고 미디어 쿼리 마이그레이션에 더 세심한 접근을 권장합니다.

사용 예:

import { useEuiMinBreakpoint, useEuiMaxBreakpoint, useEuiBreakpoint } from '@elastic/eui';

const SomeComponent = () => {
  const cssStyles = css`
    ${useEuiMaxBreakpoint('m')} {
      color: red; /* 'm' 브레이크포인트 아래에서 텍스트는 빨간색 */
    }
    ${useEuiBreakpoint(['m', 'l'])} {
      color: yellow; /* 'm'과 'xl' 브레이크포인트 사이에서 텍스트는 노란색 */
    }
    ${useEuiMinBreakpoint('xl')} {
      color: green; /* 'xl' 브레이크포인트 위에서 텍스트는 초록색 */
    }
  `;

  return <div css={cssStyles} />;
}

모든 기본 브레이크포인트 목록과 이 유틸리티들의 시각적 데모는 Breakpoint utilities를 참고하세요.

Shadows

Scrolling

이 믹스인들의 시각적 데모는 Scroll utilities를 참고하세요.

Non-hook utilities

어떤 이유로든 기존 코드에서 훅을 마이그레이션하는 것이 부담스럽다면(예: 조건부 반환, 중첩 훅 등), 각 유틸리티의 비훅(non-hook) 버전을 사용할 수 있습니다. 예를 들어 useEuiFontSize 대신 euiFontSize를, useEuiBreakpoint 대신 euiBreakpoint를, useEuiShadow 대신 euiShadow를 import할 수 있습니다.

import { euiFontSize, useEuiTheme } from '@elastic/eui';
import { css } from '@emotion/react';

const SomeComponent = ({ isLoading, hasButton }) => {
  const euiThemeContext = useEuiTheme();

  // css 사용 전의 조건부 반환
  if (isLoading) return <LoadingComponent />;

  // 중첩 훅 사용
  const someButton = useMemo(() => {
    if (!hasButton) return null;

    const cssStyles = css`
      ${euiFontSize(euiThemeContext, 'l')}
      color: red;
    `;

    return <button css={cssStyles}>Conditional button</button>;
  }, [hasButton, euiThemeContext]);

  return <>{someButton}{children}</>
};

또는 Emotion의 테마 컨텍스트 API를 활용해 useEuiTheme() 없이 현재 EUI 테마를 얻는 문법적 설탕 단축키를 사용할 수도 있습니다. 참고: Consuming with Emotion's theming

import { euiFontSize } from '@elastic/eui';
import { css } from '@emotion/react';

const SomeComponent = ({ isLoading }) => {
  if (isLoading) return null;

  return (
    <div
      css={(euiThemeContext) => css`
        ${euiFontSize(euiThemeContext, 'l')}
        color: red;
      `}
    />
  );
}

css 함수 안의 테마 매개변수에 타입 오류가 발생하면, 플러그인이 Kibana의 emotion.d.ts 파일을 사용하도록 설정해야 합니다. 이를 위해 앞서 언급한 emotion.d.ts를 플러그인 내 tsconfig.json 파일의 include 속성 값으로 typings 디렉터리 위치에 상대적인 경로로 추가하세요.

더 알아보기 (Learn more)