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

JSS에서 마이그레이션하기

원문 보기 위키 갱신

JSS에서 마이그레이션하기 (선택) (Migrating from JSS)

Material UI v4에서 v5로 업데이트할 때 JSS에서 Emotion으로 마이그레이션하는 방법을 설명하는 가이드예요.

출처: 문서

본문

Material UI v5 마이그레이션

  1. 시작하기
  2. 깨지는 변경 사항 1부: 스타일과 테마
  3. 깨지는 변경 사항 2부: 컴포넌트
  4. JSS에서 마이그레이션하기 👈 당신은 여기
  5. 문제 해결

JSS에서 Emotion으로 마이그레이션하기 (Migrating from JSS to Emotion)

v5의 가장 큰 변화 중 하나는 기본 스타일링 솔루션으로 JSS를 Emotion (또는 대안으로 styled-components)으로 대체한 것이에요.

v5로 마이그레이션한 뒤에도 컴포넌트에 대한 오버라이드를 추가할 때(예: makeStyles, withStyles) 계속 JSS를 사용할 수 있다는 점을 알아두세요. 그러다 언제든 새 스타일링 엔진으로 옮기고 싶다면 컴포넌트를 점진적으로 리팩터링할 수 있어요.

:::info

Next.js를 사용하면서 Emotion과 JSS를 함께 SSR에서 동작하도록 어떻게 설정해야 할지 모르겠다면, 이 예제 프로젝트를 살펴보세요. :::

이 문서는 JSS에서 벗어나기 위해 필요한 모든 단계를 검토해요.

다음 두 옵션 중 하나를 사용할 수 있지만, 첫 번째가 더 선호돼요.

1. styled 또는 sx API 사용

Codemod

JSS 스타일을 styled API로 마이그레이션하는 데 도움이 되는 codemod를 제공해요. 하지만 이 방식은 CSS 특이성을 증가시켜요.

:::info 보통 이런 식으로 스타일을 쓰지는 않을 거예요. 하지만 이것이 codemod로 만들 수 있는 최고의 변환이에요.

나중에 다듬고 싶다면 아래 절들에 나온 예시를 참고하면 돼요. :::

npx @mui/codemod@latest v5.0.0/jss-to-styled <path>

변환 예시:

 import Typography from '@mui/material/Typography';
-import makeStyles from '@mui/styles/makeStyles';
+import { styled } from '@mui/material/styles';

-const useStyles = makeStyles((theme) => ({
-  root: {
-    display: 'flex',
-    alignItems: 'center',
-    backgroundColor: theme.palette.primary.main
-  },
-  cta: {
-    borderRadius: theme.shape.radius
-  },
-  content: {
-    color: theme.palette.common.white,
-    fontSize: 16,
-    lineHeight: 1.7
-  },
-}))
+const PREFIX = 'MyCard';
+const classes = {
+  root: `${PREFIX}-root`,
+  cta: `${PREFIX}-cta`,
+  content: `${PREFIX}-content`,
+}
+const Root = styled('div')(({ theme }) => ({
+  [`&.${classes.root}`]: {
+    display: 'flex',
+    alignItems: 'center',
+    backgroundColor: theme.palette.primary.main
+  },
+  [`& .${classes.cta}`]: {
+    borderRadius: theme.shape.radius
+  },
+  [`& .${classes.content}`]: {
+    color: theme.palette.common.white,
+    fontSize: 16,
+    lineHeight: 1.7
+  },
+}))

 export const MyCard = () => {
-  const classes = useStyles();
   return (
-    <div className={classes.root}>
+    <Root className={classes.root}>
       {/* The benefit of this approach is that the code inside Root stays the same. */}
       <Typography className={classes.content}>...</Typography>
       <Button className={classes.cta}>Go</Button>
-    </div>
+    </Root>
   )
 }

:::success 이 codemod를 파일의 작은 묶음에 먼저 실행하고 계속하기 전에 변경 사항을 확인해야 해요. 변환 후 코드를 조정해야 하는 경우가 있으니까요. 이 codemod가 모든 경우를 다루진 못해요. :::

수동 (Manual)

반응형 스타일을 만들거나 작은 CSS를 오버라이드할 때는 styled보다 sx API를 권장해요. sx에 대해 더 알아보기.

 import Chip from '@mui/material/Chip';
-import makeStyles from '@mui/styles/makeStyles';
+import Box from '@mui/material/Box';

-const useStyles = makeStyles((theme) => ({
-  wrapper: {
-    display: 'flex',
-  },
-  chip: {
-    padding: theme.spacing(1, 1.5),
-    boxShadow: theme.shadows[1],
-  }
-}));

 function App() {
-  const classes = useStyles();
   return (
-    <div className={classes.wrapper}>
-      <Chip className={classes.chip} label="Chip" />
-    </div>
+    <Box sx={{ display: 'flex' }}>
+      <Chip label="Chip" sx={{ py: 1, px: 1.5, boxShadow: 1 }} />
+    </Box>
   );
 }

경우에 따라서는 CSS 특이성을 높이는 대신 파일에 여러 styled 컴포넌트를 만들고 싶을 수도 있어요.

예를 들어:

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

-const useStyles = makeStyles((theme) => ({
-  root: {
-    display: 'flex',
-    alignItems: 'center',
-    borderRadius: 20,
-    background: theme.palette.grey[50],
-  },
-  label: {
-    color: theme.palette.primary.main,
-  }
-}))
+const Root = styled('div')(({ theme }) => ({
+  display: 'flex',
+  alignItems: 'center',
+  borderRadius: 20,
+  background: theme.palette.grey[50],
+}))

+const Label = styled('span')(({ theme }) => ({
+  color: theme.palette.primary.main,
+}))

 function Status({ label }) {
-  const classes = useStyles();
   return (
-    <div className={classes.root}>
-      {icon}
-      <span className={classes.label}>{label}</span>
-    </div>
+    <Root>
+      {icon}
+      <Label>{label}</Label>
+    </Root>
   )
 }

:::success 이 jss-to-styled 도구는 JSS를 CSS 특이성을 높이지 않고 여러 styled 컴포넌트로 변환하는 데 도움을 줘요.

이 도구는 MUI가 유지보수하지 않아요. :::

2. tss-react 사용

:::error 이 API는 @emotion 대신 기반 스타일링 엔진으로 styled-components를 사용 중이라면 동작하지 않아요. :::

API는 JSS makeStyles와 비슷하지만, 내부적으로는 @emotion/react를 사용해요. 또한 v4의 makeStyles보다 훨씬 더 나은 TypeScript 지원을 제공해요.

사용하려면 프로젝트 의존성에 추가해야 해요.

npm을 쓰면:

npm install tss-react

yarn을 쓰면:

yarn add tss-react

Codemod

JSS 스타일을 tss-react API로 마이그레이션하는 데 도움이 되는 codemod를 제공해요.

npx @mui/codemod@latest v5.0.0/jss-to-tss-react <path>

변환 예시:

 import * as React from 'react';
-import makeStyles from '@material-ui/styles/makeStyles';
+import { makeStyles } from 'tss-react/mui';
 import Button from '@mui/material/Button';
 import Link from '@mui/material/Link';

-const useStyles = makeStyles((theme) => {
+const useStyles = makeStyles()((theme) => {
   return {
     root: {
       color: theme.palette.primary.main,
     },
     apply: {
       marginRight: theme.spacing(2),
     },
   };
 });

 function Apply() {
-  const classes = useStyles();
+  const { classes } = useStyles();

   return (
     <div className={classes.root}>
       <Button component={Link} to="https://support.mui.com" className={classes.apply}>
         Apply now
       </Button>
     </div>
   );
 }

 export default Apply;

$ 문법과 clsx를 사용해 여러 CSS 클래스를 결합하고 있었다면 변환은 이렇게 생겼어요.

 import * as React from 'react';
-import { makeStyles } from '@material-ui/core/styles';
-import clsx from 'clsx';
+import { makeStyles } from 'tss-react/mui';

-const useStyles = makeStyles((theme) => ({
+const useStyles = makeStyles<void, 'child' | 'small'>()((theme, _params, classes) => ({
   parent: {
     padding: 30,
-    '&:hover $child': {
+    [`&:hover .${classes.child}`]: {
       backgroundColor: 'red',
     },
   },
   small: {},
   child: {
     backgroundColor: 'blue',
     height: 50,
-    '&$small': {
+    [`&.${classes.small}`]: {
       backgroundColor: 'lightblue',
       height: 30
     }
   },
 }));

 function App() {
-  const classes = useStyles();
+  const { classes, cx } = useStyles();
   return (
     <div className={classes.parent}>
       <div className={classes.child}>
         Background turns red when the mouse hovers over the parent.
       </div>
-      <div className={clsx(classes.child, classes.small)}>
+      <div className={cx(classes.child, classes.small)}>
         Background turns red when the mouse hovers over the parent.
         I am smaller than the other child.
       </div>
     </div>
   );
 }

 export default App;

:::error JavaScript(가 아니라 TypeScript)를 사용할 때는 <void, 'child' | 'small'>을 제거하세요. :::

다음은 $ 문법, useStyles() 매개변수, classes prop에서 클래스 병합(문서 참고), 그리고 스타일시트의 명시적 이름을 사용하는 종합적인 예시예요.

-import clsx from 'clsx';
-import { makeStyles, createStyles } from '@material-ui/core/styles';
+import { makeStyles } from 'tss-react/mui';

-const useStyles = makeStyles((theme) => createStyles<
-  'root' | 'small' | 'child', {color: 'primary' | 'secondary', padding: number}
->(
-({
-  root: ({color, padding}) => ({
+const useStyles = makeStyles<{color: 'primary' | 'secondary', padding: number}, 'child' | 'small'>({name: 'App'})((theme, { color, padding }, classes) => ({
+  root: {
     padding: padding,
-    '&:hover $child': {
+    [`&:hover .${classes.child}`]: {
       backgroundColor: theme.palette[color].main,
     }
-  }),
+  },
   small: {},
   child: {
     border: '1px solid black',
     height: 50,
-    '&$small': {
+    [`&.${classes.small}`]: {
       height: 30
     }
   }
-}), {name: 'App'});
+}));

 function App({classes: classesProp}: {classes?: any}) {
-  const classes = useStyles({color: 'primary', padding: 30, classes: classesProp});
+  const { classes, cx } = useStyles({
+    color: 'primary',
+    padding: 30
+  }, {
+    props: {
+      classes: classesProp
+    }
+  });

   return (
     <div className={classes.root}>
       <div className={classes.child}>
         The Background take the primary theme color when the mouse hovers the parent.
       </div>
-      <div className={clsx(classes.child, classes.small)}>
+      <div className={cx(classes.child, classes.small)}>
         The Background take the primary theme color when the mouse hovers the parent.
         I am smaller than the other child.
       </div>
     </div>
   );
 }

 export default App;

codemod를 실행한 후 코드에서 "TODO jss-to-tss-react codemod"를 검색하면 codemod가 안정적으로 처리하지 못한 경우를 찾을 수 있어요.

TODO 주석이 있는 경우 외에도 codemod가 완전히 처리하지 못하는 경우가 있을 수 있어요. 특히 스타일의 일부가 함수에서 반환되는 경우가 그렇죠.

함수 안에 묻혀 있는 스타일이 $ 문법이나 useStyles 매개변수를 사용한다면 그 스타일은 적절하게 마이그레이션되지 않아요.

:::error clsx를 버리고 cx를 사용해야 해요.

cx의 핵심 장점은 Emotion이 생성한 클래스 이름을 감지해서 스타일이 올바른 순서로 덮어써지도록 보장한다는 거예요.

여러 CSS 클래스의 스타일 기본 우선순위는 JSS와 tss-react 사이에 차이가 있고, cx 매개변수를 어느 정도 수동으로 재정렬해야 할 수도 있어요. 자세한 내용은 이 이슈 코멘트를 참고하세요. :::

클래스 이름이 항상 컴포넌트의 실제 이름을 포함하도록 하려면 암시적 이름 키(name: { App })로 name을 제공할 수 있어요.

자세한 내용은 이 tss-react 문서를 참고하세요.

두 개 이상의 항목을 구조 분해하면 이런 ESLint 경고가 나올 수 있어요.

일반 프로젝트에서 이렇게 eslint(prefer-const)를 비활성화하는 걸 주저하지 마세요.

withStyles()

tss-react는 v4의 withStyles()의 타입 안전 구현도 제공해요.

:::info $ 문법에 해당하는 것도 tss의 withStyles()에서 지원돼요. 문서 참고. :::

-import Button from '@material-ui/core/Button';
+import Button from '@mui/material/Button';
-import withStyles from '@material-ui/styles/withStyles';
+import { withStyles } from 'tss-react/mui';

 const MyCustomButton = withStyles(
+  Button,
   (theme) => ({
     root: {
       minHeight: '30px',
     },
     textPrimary: {
       color: theme.palette.text.primary,
     },
     '@media (min-width: 960px)': {
       textPrimary: {
         fontWeight: 'bold',
       },
     },
   }),
-)(Button);
+);
 
 export default MyCustomButton;

테마 스타일 오버라이드 (Theme style overrides)

전역 테마 오버라이드는 TSS에서 기본으로 지원돼요.

깨지는 변경 사항 문서의 해당 절에 있는 지침을 따르고, makeStyles에 name을 제공하세요.

Material UI v5에서는 스타일 오버라이드도 콜백을 받아들이기 시작했어요.

기본적으로 TSS는 테마만 제공할 수 있어요. props와 ownerState를 제공하고 싶다면 이 문서를 참고하세요.

:::warning tss-react는 MUI가 유지보수하지 않아요.

SSR(Next.js)을 어떻게 설정하는지에 대한 질문이 있거나 theme 객체를 어떻게 커스터마이징할지 궁금하다면 tss-react 문서를 참고하세요.

버그나 기능 요청은 이슈를 제출할 수 있고, 도움이 필요하면 토론을 시작할 수도 있어요. :::

마이그레이션 완료하기 (Complete the migration)

모든 스타일링을 마이그레이션한 뒤에는 패키지를 제거해서 불필요한 @mui/styles를 정리하세요.

npm을 쓰면:

npm uninstall @mui/styles

yarn을 쓰면:

yarn remove @mui/styles

:::warning @emotion/styled는 @mui/material의 peer dependency예요. 명시적으로 사용하지 않더라도 의존성에 계속 두어야 해요. :::

더 알아보기 (Learn more)