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

네이티브 색상으로 업그레이드하기

원문 보기 위키 갱신

네이티브 색상으로 업그레이드하기 (Upgrade to native color)

JavaScript 색상 조작에서 네이티브 색상으로 업그레이드하는 방법을 설명하는 가이드예요.

출처: 문서

본문

네이티브 색상(native color)은 JavaScript 색상 조작을 CSS color-mix()와 상대 색상(relative colors)으로 대체하는 옵트인(opt-in) 기능이에요. 자세한 내용은 네이티브 색상 문서를 확인해 보세요.

사전 준비 (Prerequisites)

Material UI를 최신 버전(최소 v7.3.0)으로 업데이트하세요.

npm install @mui/material@next

네이티브 색상 활성화 (Enable native color)

createTheme() 함수에서 cssVariables.nativeColor 옵션을 true로 설정해요.

const theme = createTheme({
  cssVariables: { nativeColor: true },
});

네이티브 색상을 활성화하면 Material UI는 CSS color-mix()와 상대 색상을 사용해서 색상을 조작하기 시작해요.

제대로 동작하는지 확인하려면 브라우저의 개발자 도구를 여세요. Elements 탭에서 Styles 패널을 클릭하고 "color-mix"를 검색해 보면, Material UI 색상 토큰이 CSS 변수로 나타나는 걸 볼 수 있을 거예요.

JavaScript 색상 조작 다루기 (Handling JavaScript color manipulation)

@mui/*에서 가져온 alpha, lighten, darken 함수로 네이티브 색상으로 업데이트된 색상을 조작한다면 애플리케이션이 깨질 수 있어요.

예를 들어 contrastText 토큰을 조작하면 애플리케이션이 깨져요.

import { alpha } from '@mui/material/styles';

const theme = createTheme({
  cssVariables: { nativeColor: true },
});

// ❌ This will break because `alpha` does not support relative colors.
console.log(alpha(theme.palette.primary.contrastText, 0.3));

이 문제를 해결하려면 theme.alpha() 어댑터 함수로 색상을 조작하면 돼요.

const theme = createTheme({
  cssVariables: { nativeColor: true },
});

// ✅ This will work because `theme.alpha` supports relative colors.
console.log(theme.alpha(theme.palette.primary.contrastText, 0.3));

lighten과 darken 함수도 마찬가지예요. 아래 codemod를 따라하면 여러 파일을 한 번에 업데이트할 수 있어요.

채널 토큰 사용 제거 (Remove usage of channel tokens)

네이티브 색상을 활성화한 뒤에는 *Channel 토큰에 의존하면 안 돼요. 그 값이 채널(공백으로 구분된 숫자)임이 보장되지 않기 때문이에요.

대신 테마 색상 함수로 색상을 조작해서 이렇게 사용해요.

- `rgba(${theme.vars.palette.primary.mainChannel} / 0.3)`
+ `theme.alpha((theme.vars || theme).palette.primary.main, 0.3)`

Codemod

이 codemod는 @mui/system/colorManipulator나 @mui/material/styles에서 가져온 alpha(), lighten(), darken() 함수를 테마 색상 함수로 대체해요.

npx @mui/codemod@latest v7.0.0/theme-color-functions <path>

다음 변환 예시는 codemod가 실제로 하는 일을 보여줘요.

- import { alpha } from '@mui/system/colorManipulator';
- // or import { alpha } from '@mui/material/styles';

 styled('div')(({ theme }) => ({
   width: '100%',
   height: '100%',
   '&.good': {
-    backgroundColor: theme.vars
-      ? `rgba(${theme.vars.palette.success.mainChannel} /  0.3)`
-      : alpha(theme.palette.success.main, 0.3),
+    backgroundColor: theme.alpha((theme.vars || theme).palette.success.main, 0.3),
   },
   '&.bad': {
-    backgroundColor: theme.vars
-      ? `rgba(${theme.vars.palette.error.mainChannel} /  0.3)`
-      : alpha(theme.palette.error.main, 0.3),
+    backgroundColor: theme.alpha((theme.vars || theme).palette.error.main, 0.3),
   },
 }));

더 알아보기 (Learn more)