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

Pigment CSS 시작하기

원문 보기 위키 갱신

Pigment CSS를 사용해서 컴포넌트를 커스터마이즈하는 방법을 익혀 보세요.

출처: 문서

본문

:::warning Pigment CSS는 현재 개발 초기 알파(alpha) 단계예요. 우리는 성능과 안정성 개선을 위해 적극적으로 작업하고 있어요. 문제를 발견하면 GitHub 이슈를 열어 주세요. :::

Pigment CSS는 빌드 시점에 사전 컴파일되는 제로 런타임(zero-runtime) CSS-in-JS 라이브러리예요. React Server Components와 호환되며, 다른 스타일링 엔진 대비 상당한 성능 개선을 제공해요.

Pigment CSS는 어떤 React 컴포넌트 라이브러리와도 호환되며 Vite와 Next.js와 함께 사용할 수 있어요.

기존 Material UI 프로젝트가 있다면 Migrating to Pigment CSS 가이드를 확인해 보세요.

사전 요구사항

  • Node.js
  • 패키지 매니저
  • Next.js 또는 Vite 프로젝트

다음 명령으로 Pigment CSS 설치와 프로젝트 생성을 빠르게 진행할 수 있어요.

curl https://codeload.github.com/mui/pigment-css/tar.gz/master | tar -xz --strip=2  pigment-css-master/examples/pigment-css-nextjs-ts
cd pigment-css-nextjs-ts
curl https://codeload.github.com/mui/pigment-css/tar.gz/master | tar -xz --strip=2 pigment-css-master/examples/pigment-css-vite-ts
cd pigment-css-vite-ts

수동 설치

기존 프로젝트에서 시작하려면 다음 명령으로 Pigment CSS를 설치해 주세요.

npm install @pigment-css/react
npm install --save-dev @pigment-css/nextjs-plugin
npm install @pigment-css/react
npm install --save-dev @pigment-css/vite-plugin

다음으로 구성 파일로 가서 withPigment 플러그인을 임포트해 주세요.

// next.config.js
import { withPigment } from '@pigment-css/nextjs-plugin';

export default withPigment(nextConfig);
// main.tsx
import { pigment } from '@pigment-css/vite-plugin';

export default defineConfig({
  plugins: [
    pigment(),
    // ... Your other plugins.
  ],
});

마지막으로 layout.tsx(Next.js) 또는 main.tsx(Vite) 파일에서 Pigment CSS 스타일시트를 임포트해 주세요.

import '@pigment-css/react/styles.css';

사용법

Pigment CSS는 현대 React 개발의 요구를 충족해요. React Server Components와 호환되며, 런타임 성능 비용 없이 CSS-in-JS의 이점을 누릴 수 있게 해 줘요.

Pigment CSS를 사용하면 로컬 범위의 재사용 가능한 스타일, 테마, CSS 변수 등을 만들 수 있어요.

스타일링

Pigment CSS는 다양한 API를 통해 스타일의 생성과 정의를 단순화해요.

  • css: 재사용 가능한 스타일용
  • globalCss: 전역 스타일용
  • keyframes: 재사용 가능한 애니메이션 keyframes용
  • styled: styled 컴포넌트용

재사용 가능한 스타일 만들기

css API를 사용해 재사용 가능한 스타일을 만들어 보세요.

import { css } from '@pigment-css/react';

템플릿 문법이나 객체 문법 둘 다 사용할 수 있어요.

템플릿 문법

const bodyBackground = css`
  background-color: #000;
  color: #fff;
`;

객체 문법

const mainClass = css({
  display: '#000',
  color: '#fff',
});

전역 스타일 만들기

globalCss API를 사용해 앱 전체에 로드할 전역 스타일을 정의해 보세요.

JavaScript 파일의 최상위 레벨에 정의해야 해요.

import { globalCss } from '@pigment-css/react';

globalCss`
  body {
    margin: 0;
    padding: 0;
  }
`;

styled 컴포넌트 만들기

스타일을 컴포넌트에 범위 지정하면 필요한 CSS만 로드되고, 모듈성·가독성·유지보수성이 좋아져요. props나 런타임 값을 기반으로 컴포넌트에 조건부 스타일을 적용할 수 있어요.

styled API를 사용해 styled 컴포넌트를 만들어 보세요.

import { styled } from '@pigment-css/react';

const Heading = styled('div')({
  fontSize: '2rem',
  color: '#9FADBC',
  fontWeight: 'bold',
  margin: '1rem',
});

props 기반 스타일링

variants 키를 사용해 props에 기반한 다양한 스타일 옵션을 정의할 수 있어요. 이 접근 방식은 prop의 값이 빌드 시점에 알려져 있을 때 권장돼요.

각 variants는 props와 style 키를 가진 객체예요.

import { styled } from '@pigment-css/react';

const Heading = styled('div')({
  fontSize: '2rem',
  color: '#9FADBC',
  fontWeight: 'bold',
  margin: '1rem',
  variants: [
    {
      props: { variant: 'success' },
      style: { color: '#23AD79' },
    },
    {
      props: { size: 'small' },
      style: { fontSize: '1.5rem' },
    },
  ],
});

런타임 값 기반 스타일링

prop의 값이 미리 알려지지 않았다면, 런타임 값을 기반으로 컴포넌트를 스타일링할 수 있어요.

const Heading = styled('h1')({
  color: ({ isError }) => (isError ? 'red' : 'black'),
});

테마

Pigment CSS는 테마를 지원해서 앱 전체에 일관된 스타일과 값을 적용할 수 있어요. 구성 파일에서 테마를 정의하면 돼요.

import { withPigment } from '@pigment-css/nextjs-plugin';

export default withPigment(nextConfig, {
  theme: {
    colors: {
      primary: 'tomato',
      secondary: 'cyan',
    },
    spacing: {
      unit: 8,
    },
    typography: {
      fontFamily: 'Inter, sans-serif',
    },
    // ...more keys and values, it's free style!
  },
});

테마에 접근하려면 styled()와 css() API와 함께 콜백을 사용해 주세요.

const Heading = styled('h1')(({ theme }) => ({
  color: theme.colors.primary,
  fontSize: theme.spacing.unit * 4,
  fontFamily: theme.typography.fontFamily,
}));

CSS 변수 지원

테마 값이 extendTheme 유틸리티로 감싸지면 Pigment CSS는 그 값들에서 CSS 변수를 생성하고 vars 객체를 만들어요.

import { withPigment, extendTheme } from '@pigment-css/nextjs-plugin';

export default withPigment(nextConfig, {
  theme: extendTheme({
    colors: {
      primary: 'tomato',
      secondary: 'cyan',
    },
    spacing: {
      unit: 8,
    },
    typography: {
      fontFamily: 'Inter, sans-serif',
    },
  }),
});

색상 스킴

extendTheme 유틸리티 안의 colorSchemes 키를 사용해 다크 모드와 라이트 모드 전환 같은 서로 다른 조건에 따라 다른 값을 지정할 수 있어요.

extendTheme({
  colorSchemes: {
    light: {
      colors: {
        background: '#f9f9f9',
        foreground: '#121212',
      },
    },
    dark: {
      colors: {
        background: '#212121',
        foreground: '#fff',
      },
    },
  },
});

Pigment CSS는 기본적으로 prefers-color-scheme 미디어 쿼리를 사용해서 색상 스킴을 전환해요.

const colorScheme = css`
  background-color: ${({ theme }) => theme.colorSchemes.dark.colors.background};
  color: ${({ theme }) => theme.colorSchemes.dark.colors.foreground};

  @media (prefers-color-scheme: light) {
    background-color: ${({ theme }) => theme.colorSchemes.light.colors.background};
    color: ${({ theme }) => theme.colorSchemes.light.colors.foreground};
  }
`;

getSelector 함수를 제공해서 동작을 커스터마이즈할 수도 있어요.

 extendTheme({
   colorSchemes: {
     light: { ... },
     dark: { ... },
   },
+  getSelector: (colorScheme) => colorScheme ? `.theme-${colorScheme}` : ':root',
 });

sx prop

Pigment CSS는 the sx prop을 포함해서 어떤 요소에도 일회성 인라인 커스텀 스타일을 제공할 수 있게 해 줘요.

빌드 시점에 Pigment CSS는 sx prop을 className과 style prop으로 바꿔요. sx prop은 모든 Material UI 컴포넌트뿐 아니라 HTML 요소와 서드파티 JSX 컴포넌트에서도 동작해요.

<div sx={{ display: 'flex', flexDirection: 'column' }}>

<AnyComponent sx={{ fontSize: 12, color: 'red' }} />;

HTML 요소에 sx prop을 사용한다면 HTMLAttributes 인터페이스를 확장해야 해요.

type Theme = {
  // your theme type
};

declare global {
  namespace React {
    interface HTMLAttributes<T> {
      sx?:
        | React.CSSProperties
        | ((theme: Theme) => React.CSSProperties)
        | ReadonlyArray<
            React.CSSProperties | ((theme: Theme) => React.CSSProperties)
          >;
    }
  }
}

런타임 테마

:::info

주의사항

  • 강력한 이유가 없다면 런타임 테마 사용을 피하세요.
  • 런타임 테마는 직렬화 가능한 값(serializable values)만 담아요(컴포넌트 내부 로직을 위한 일부 함수가 breakpoints와 transitions에 여전히 존재하지만 미래에 제거될 수 있어요).
  • 런타임 테마는 빌드 시점에 사전 컴파일되므로 모드(라이트와 다크) 간에 바뀌지 않아요. 테마 구조와 값을 기반으로 무언가를 렌더링하려면 CSS 변수를 참조하는 theme.vars.*를 사용하세요.

:::

런타임 테마에 접근하려면 useTheme 훅을 사용해 주세요.

import { useTheme } from '@mui/material-pigment-css';

function MyComponent() {
  const theme = useTheme();

  return (
    <div>
      {Object.entries(theme.vars.palette.primary).map(([key, value]) => (
        <div key={key} style={{ width: 40, height: 40, background: value }}>
          {key}: {value}
        </div>
      ))}
    </div>
  );
}

더 알아보기 (Learn more)