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

Pigment CSS로 마이그레이션하기

원문 보기 위키 갱신

Pigment CSS로 마이그레이션하기 (Migrating to Pigment CSS)

이 가이드는 Pigment CSS를 Material UI와 통합하는 방법을 도와줘요.

출처: 문서

본문

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

이 가이드를 진행하기 전에 Material UI v7로 업그레이드(또는 v6)했는지 확인하세요.

소개 (Introduction)

Material UI의 기본 스타일링 엔진은 Emotion이에요. CSS-in-JS 방식으로 스타일을 작성하게 해 주는데, 상태와 props에 의존하는 동적 스타일에 아주 좋아요. 하지만 빈번한 리렌더 상황에서는 성능 단점이 있어요. 스타일 재계산이 클라이언트 측에서 일어나기 때문이에요. 또한 서버에서 컴포넌트를 미리 렌더링하는 새로운 렌더링 패러다임인 React Server Components를 완전히 지원하지도 않아요.

Pigment CSS는 CSS-in-JS 방식으로 스타일을 작성하는 동일한 개발자 경험을 유지하면서 이런 문제들을 해결하는 것을 목표로 해요. 마이그레이션 과정을 쉽게 하기 위해 Emotion과 함께 동작할 수 있지만, 결국에는 완전히 Pigment CSS로 마이그레이션하는 것이 권장돼요.

지원 프레임워크 (Supported frameworks)

Pigment CSS는 다음 프레임워크 중 하나로 사용할 수 있어요.

설치 (Installation)

먼저 Pigment CSS용 Material UI 래퍼 패키지를 설치해요.

npm install @mui/material-pigment-css @pigment-css/react

그런 다음 프레임워크에 따른 지침을 따라가요.

Next.js

Next.js 플러그인을 dev dependency로 설치해요.

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

그런 다음 Next.js 설정 파일을 열고 플러그인을 추가해요.

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

const nextConfig = {
  // ...Your nextjs config.
};

/**
 * @type {import('@pigment-css/nextjs-plugin').PigmentOptions}
 */
const pigmentConfig = {
  transformLibraries: ['@mui/material'],
};

export default withPigment(nextConfig, pigmentConfig);
const { withPigment } = require('@pigment-css/nextjs-plugin');

const nextConfig = {
  // ...Your nextjs config.
};

/**
 * @type {import('@pigment-css/nextjs-plugin').PigmentOptions}
 */
const pigmentConfig = {
  transformLibraries: ['@mui/material'],
};

module.exports = withPigment(nextConfig, pigmentConfig);

마지막으로 레이아웃 파일 최상단에서 스타일시트를 import해요.

 import type { Metadata } from 'next';
 import { Inter } from 'next/font/google';

+import '@mui/material-pigment-css/styles.css';

 export default function RootLayout(props) {
   return (
     <html lang="en">
       <body className={`${inter.className}`}>
         {props.children}
       </body>
     </html>
   );
 }

Vite

Vite 플러그인을 dev dependency로 설치해요.

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

다음으로 Vite 설정 파일(보통 vite.config.mjs 또는 vite.config.js)을 열고 플러그인을 추가해요.

import { defineConfig } from 'vite';
import { pigment } from '@pigment-css/vite-plugin';

/**
 * @type {import('@pigment-css/vite-plugin').PigmentOptions}
 */
const pigmentConfig = {
  transformLibraries: ['@mui/material'],
};

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

:::warning 이 패키지 관리자에서는 플러그인이 제대로 동작하지 못하게 하는 pnpm 관련 알려진 문제가 있어요. 해결될 때까지는 npm이나 yarn을 대신 사용해야 해요. :::

마지막으로 Pigment CSS 스타일시트를 메인 파일 최상단에 추가해요.

 import * as React from 'react';
+import '@mui/material-pigment-css/styles.css';
 import App from './App';

 ReactDOM.createRoot(document.getElementById('root')).render(
   <React.StrictMode>
     <App />
   </React.StrictMode>,
 );

테마 설정하기 (Configuring the theme)

Pigment CSS를 Material UI와 통합하려면 테마를 플러그인에 설정해야 해요. Next.js 또는 Vite 설정 파일에 다음 코드를 추가해요.

+import { createTheme } from '@mui/material';

 const pigmentConfig = {
   transformLibraries: ['@mui/material'],
+  theme: createTheme({
+    cssVariables: true,
+    /* other parameters, if any */
+  }),
 };

커스텀 테마가 있다면 다음 테마 마이그레이션 지침을 따라가세요. 그렇지 않다면 이제 개발 서버를 시작할 준비가 된 거예요.

npm run dev

브라우저를 열고 localhost URL로 이동하면 Pigment CSS로 앱이 실행되는 걸 볼 수 있을 거예요.

Next.js 글꼴 최적화

next/font로 글꼴 로딩을 최적화하고 있다면, 글꼴 설정의 variable 속성에 CSS 변수 이름을 전달하고 body className에서 사용해요.

 import { Roboto } from 'next/font/google';

 const roboto = Roboto({
   weight: ['300', '400', '500', '700'],
   subsets: ['latin'],
   display: 'swap',
+  variable: '--my-font-family',
 });

 export default function RootLayout(props) {
   const { children } = props;
   return (
     <html lang="en">
+      <body className={roboto.variable}>
         {children}
       </body>
     </html>
   );
 }

마지막으로 이전 단계에서 만든 변수로 typography.fontFamily 값을 업데이트해요.

 const pigmentConfig = {
   transformLibraries: ['@mui/material'],
   theme: createTheme({
+    typography: {
+      fontFamily: 'var(--my-font-family)',
+    },
   }),
 };

TypeScript

TypeScript를 사용한다면 Pigment CSS 테마 타입을 Material UI Theme으로 확장해야 해요. tsconfig.json에 포함된 파일에 다음 코드를 추가해요.

// e.g. App.tsx
import { Theme } from '@mui/material/styles';

declare module '@mui/material-pigment-css' {
  interface ThemeArgs {
    theme: Theme;
  }
}

그런 다음 다음 코드로 타입이 Pigment CSS에 제대로 인식되는지 확인해요.

// e.g. App.tsx
import { styled } from '@mui/material-pigment-css';

const TestThemeTypes = styled('div')(({ theme }) => ({
  color: theme.palette.primary.main,
}));

편집기에 TypeScript 오류가 없어야 해요. 마지막으로 테스트 코드를 제거해요.

동작 방식 (How it works)

Pigment CSS 플러그인이 프레임워크 번들러를 통해 설정되면, Material UI가 사용하는 스타일링 API를 가로채서 Pigment CSS의 것으로 대체해요. 그러면 Pigment CSS는 빌드 시점에 스타일을 추출해서 스타일시트에 주입해요.

Material UI v5에서 온 경우, Pigment CSS를 사용하는 것은 스타일 작성 측면에서 패러다임의 전환이 될 거예요. Pigment CSS는 빌드 시점 추출 도구이기 때문에 런타임 변수에 의존하는 동적 스타일을 지원하지 않아요. 예를 들어 Pigment CSS는 아래 같은 상태에 의존하는 스타일에 대해 오류를 던져요.

import Card from '@mui/material/Card';

function App() {
  const [color, setColor] = useState('#000000');

  return (
    <Card
      sx={{
        color, // ❌ Pigment CSS cannot extract this style.
      }}
    />
  );
}

새로운 스타일링 패러다임과 동적 스타일을 만드는 패턴을 배우려면 아래 가이드를 계속 읽어보시길 권장해요.

커스텀 테마 마이그레이션 (Migrating custom theme)

owner state 제거 (Removing owner state)

Pigment CSS는 빌드 시점 추출 도구이기 때문에 콜백을 통한 owner state를 지원하지 않아요. 빌드 시점에 오류를 던지는 예시가 있어요.

const theme = createTheme({
  components: {
    MuiCard: {
      styleOverrides: {
        root: {
          color: ({ ownerState }) => ({
            // ❌ Pigment CSS cannot extract this style.
            ...(ownerState.variant === 'outlined' && {
              borderWidth: 3,
            }),
          }),
        },
      },
    },
  },
});

다음 codemod를 실행해서 테마에서 owner state를 제거해요.

npx @mui/codemod@latest v6.0.0/theme-v6 next.config.mjs

codemod가 owner state를 제거하지 못하는 경우도 있어요. 그런 경우에는 owner state를 수동으로 variants로 대체해야 해요.

팔레트 기반 동적 색상 (Dynamic color based on palette)

테마 팔레트에 기반한 동적 색상이 있다면 variants 속성을 사용해 각 팔레트에 대한 스타일을 정의할 수 있어요.

const theme = createTheme({
  components: {
    MuiCard: {
      styleOverrides: {
        root: ({ theme, ownerState }) => ({
          color: theme.palette[ownerState.palette]?.main,
        }),
      },
    },
  },
});
const theme = createTheme({
  components: {
    MuiCard: {
      styleOverrides: {
        root: ({ theme }) => ({
          variants: [
            ...Object.entries(theme.palette)
              .filter(([, palette]) => palette && palette.main)
              .map(([palette, { main }]) => ({
                props: { palette },
                style: {
                  color: main,
                },
              })),
          ],
        }),
      },
    },
  },
});

기본 props provider (Default props provider)

메인 애플리케이션 파일에서 DefaultPropsProvider를 사용하고 모든 컴포넌트 기본 props를 그 안으로 옮겨요.

 import { createTheme } from '@mui/material';

 const customTheme = createTheme({
   // ...other tokens.
   components: {
     MuiButtonBase: {
-      defaultProps: {
-        disableRipple: true,
-      },
     },
     MuiSelect: {
-      defaultProps: {
-        IconComponent: DropdownIcon,
-      },
     }
   }
 });
+ import DefaultPropsProvider from '@mui/material/DefaultPropsProvider';

  function App() {
    return (
+     <DefaultPropsProvider value={{
+       MuiButtonBase: {
+         disableRipple: true,
+       },
+       MuiSelect: {
+         IconComponent: DropdownIcon,
+       },
+     }}>
        {/* Your app */}
+     </DefaultPropsProvider>
    );
  }

동적 스타일 마이그레이션 (Migrating dynamic styles)

sx prop

다음 codemod를 실행해요.

npx @mui/codemod@latest v6.0.0/sx-prop path/to/folder

아래 시나리오들은 codemod가 다루지 않으므로 수동으로 업데이트해야 해요.

동적 값 (Dynamic values)

값이 변수에 의존한다면 인라인 스타일 안의 CSS 변수로 옮겨야 해요.

<div>
  {items.map((item, index) => (
    <Box
      key={index}
      sx={{
        borderRadius: '50%',
        width: `max(${6 - index}px, 3px)`,
        height: `max(${6 - index}px, 3px)`,
        bgcolor: index === 0 ? 'primary.solidBg' : 'background.level3',
      }}
    />
  ))}
</div>
<div>
  {items.map((item, index) => (
    <Box
      key={index}
      sx={{
        borderRadius: '50%',
        width: `max(6px - var(--offset), 3px)`,
        height: `max(6px - var(--offset), 3px)`,
        bgcolor: `var(--bg)`,
      }}
      style={{
        '--offset': `${index}px`,
        '--bg':
          index === 0
            ? 'var(--mui-palette-primary-solidBg)'
            : 'var(--mui-palette-background-level3)',
      }}
    />
  ))}
</div>

커스텀 컴포넌트 (Custom components)

Pigment CSS에서는 어떤 JSX 요소든 sx prop을 받을 수 있어서, Material UI 컴포넌트에 sx prop을 전달할 필요가 더 이상 없어요.

 import ButtonBase from '@mui/material/ButtonBase';

 function ActiveButton({ sx, ...props }) {
   return (
     <ButtonBase
       sx={[
         {
           '&:active': {
             opacity: 0.5,
           },
         },
-        ...Array.isArray(sx) ? sx : [sx],
       ]}
       {...props}
     />
   );
 }

styled

@mui/material/styles의 styled를 사용하는 커스텀 컴포넌트가 있다면 import 소스를 @mui/material-pigment-css로 바꿔요.

-import { styled } from '@mui/material/styles';
+import { styled } from '@mui/material-pigment-css';

그런 다음 다음 codemod를 실행해요.

npx @mui/codemod@latest v6.0.0/styled path/to/folder

아래 시나리오들은 codemod가 다루지 않으므로 수동으로 업데이트해야 해요.

props 기반 동적 스타일 (Dynamic styles based on props)

props에 기반한 동적 스타일이 있다면 CSS 변수로 옮겨야 해요. CSS 변수로 인라인 스타일을 설정하는 래퍼 컴포넌트를 만들어야 해요.

const FlashCode = styled('div')(
  ({ theme, startLine = 0, endLine = startLine, lineHeight = '0.75rem' }) => ({
    top: `calc(${lineHeight} * 1.5 * ${startLine})`,
    height: `calc(${lineHeight} * 1.5 * ${endLine - startLine + 1})`,
    ...theme.typography.caption,
  }),
);

export default FlashCode;
const FlashCodeRoot = styled('div')(({ theme }) => ({
  top: `calc(var(--Flashcode-lineHeight) * 1.5 * var(--Flashcode-startLine))`,
  height: `calc(var(--Flashcode-lineHeight) * 1.5 * (var(--Flashcode-endLine) - var(--Flashcode-startLine) + 1))`,
  ...theme.typography.caption,
}));

const FlashCode = React.forwardRef(function FlashCode(props, ref) {
  const {
    children,
    startLine = 0,
    endLine = startLine,
    lineHeight = '0.75rem',
    ...other
  } = props;

  return (
    <FlashCodeRoot
      ref={ref}
      {...other}
      style={{
        '--Flashcode-lineHeight': lineHeight,
        '--Flashcode-startLine': startLine,
        '--Flashcode-endLine': endLine,
        ...other.style,
      }}
    >
      {children}
    </FlashCodeRoot>
  );
});

export default FlashCode;

레이아웃 컴포넌트 마이그레이션 (Migrating layout components)

Pigment CSS와 호환되는 레이아웃 컴포넌트를 사용하려면 다음 컴포넌트들을 어댑터 패키지의 것으로 교체해요.

-import Container from '@mui/material/Container';
+import Container from '@mui/material-pigment-css/Container';

-import Grid from '@mui/material/Grid';
+import Grid from '@mui/material-pigment-css/Grid';

-import Stack from '@mui/material/Stack';
+import Stack from '@mui/material-pigment-css/Stack';

-import Hidden from '@mui/material/Hidden';
+import Hidden from '@mui/material-pigment-css/Hidden';

:::info @mui/material-pigment-css/Grid의 Grid 컴포넌트는 기본 Grid 컴포넌트와 동작이 달라요. 항목 사이의 간격에 margin 대신 CSS gap을 사용해요. :::

Box 컴포넌트 마이그레이션 (Migrating Box component)

다음 접근 방식 중 하나를 선택하세요.

Box 계속 사용하기

Box 컴포넌트를 어댑터 패키지의 것으로 교체해요.

-import Box from '@mui/material/Box';
+import Box from '@mui/material-pigment-css/Box';

HTML 요소 사용하기

Pigment CSS는 어떤 JSX 요소에서든 sx prop을 추출할 수 있어서, Box 컴포넌트를 사용할 필요가 없어요.

-import Box from '@mui/material/Box';

 function CustomCard() {
   return (
-    <Box sx={{ display: 'flex' }}>
-      <Box component="img" src="..." sx={{ width: 24, height: 24 }}>
-      ...
-    </Box>
+    <div sx={{ display: 'flex' }}>
+      <img src="..." sx={{ width: 24, height: 24 }}>
+      ...
+    </div>
   );
 }

TypeScript 사용자는 sx prop을 지원하도록 HTMLAttributes 인터페이스를 확장해야 해요. tsconfig.json에 포함된 파일에 다음 코드를 추가해요.

import type { Theme, SxProps } from '@mui/material/styles';

declare global {
  namespace React {
    interface HTMLAttributes<T> {
      sx?: SxProps<Theme>;
    }
    interface SVGProps<T> {
      sx?: SxProps<Theme>;
    }
  }
}

useTheme 훅 마이그레이션 (Migrate useTheme hook)

useTheme 훅을 사용하고 있다면 import 소스를 교체해요.

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

:::info Next.js App Router에서 useTheme 훅은 React Client Components에서만 동작해요. 훅을 사용하는 컴포넌트에 'use client' 지시문을 추가해야 해요. :::

오른쪽에서 왼쪽(RTL) 지원 (Right-to-left support)

오른쪽에서 왼쪽 지원을 활성화하려면 설정 파일을 다음 코드로 업데이트해요.

 const pigmentConfig = {
   theme: createTheme(),
+  css: {
+    // Specify your default CSS authoring direction
+    defaultDirection: 'ltr',
+    // Generate CSS for the opposite of the `defaultDirection`
+    // This is set to `false` by default
+    generateForBothDir: true,
+  },
 }

테마 방향에서 마이그레이션 (Migrating from theme direction)

컴포넌트에서 theme.direction을 사용하고 있다면 RtlProvider로 애플리케이션을 감싸고 방향을 얻으려면 useRtl 훅을 대신 사용해요.

+ import RtlProvider from '@mui/material-pigment-css/RtlProvider';

 function App() {
+  const [rtl, setRtl] = React.useState(false);
   return (
+    <RtlProvider value={rtl}>
       {/* Your app */}
+    </RtlProvider>
   )
 }
- import { useTheme } from '@mui/material/styles';
+ import { useRtl } from '@mui/material-pigment-css/RtlProvider';

 function App() {
-  const theme = useTheme();
+  const isRtl = useRtl();

   return (
     <Box sx={{ display: 'flex', alignItems: 'center', pl: 1, pb: 1 }}>
       <IconButton aria-label="previous">
-        {theme.direction === 'rtl' ? <SkipNextIcon /> : <SkipPreviousIcon />}
+        {isRtl ? <SkipNextIcon /> : <SkipPreviousIcon />}
       </IconButton>
       <IconButton aria-label="play/pause">
         <PlayArrowIcon sx={{ height: 38, width: 38 }} />
       </IconButton>
       <IconButton aria-label="next">
-        {theme.direction === 'rtl' ? <SkipPreviousIcon /> : <SkipNextIcon />}
+        {isRtl ? <SkipPreviousIcon /> : <SkipNextIcon />}
       </IconButton>
     </Box>
   );
 }

더 알아보기 (Learn more)