styled-components 사용하기

styled-components 사용하기 (Using styled-components)

Emotion 대신 styled-components를 Material UI와 함께 사용하는 방법을 알아봅니다.

출처: 문서

본문

Emotion 대신 styled-components를 Material UI와 함께 사용하는 방법을 배워볼게요.

:::error 2021년 말 기준으로, styled-components는 서버 렌더링하는 Material UI 프로젝트와 호환되지 않습니다. 그 이유는 babel-plugin-styled-components가 @mui 패키지 내부의 styled() 유틸리티와 동작할 수 없기 때문이에요. 자세한 내용은 이 GitHub issue를 참고하세요.

SSR 프로젝트에서는 Emotion 사용을 강력히 권장합니다. :::

기본적으로 Material UI는 Emotion을 사용해 CSS 스타일을 생성합니다. 모든 컴포넌트는 styled() API에 의존해 페이지에 CSS를 주입합니다. 이 API는 여러 인기 스타일링 라이브러리가 지원하므로, Material UI에서 그 사이를 전환할 수 있게 해줍니다.

선택한 스타일링 솔루션을 Material UI와 호환되게 감싸는 두 가지 패키지를 제공합니다.

  • @mui/styled-engine: Emotion의 styled() API를 감싸는 얇은 래퍼입니다. <GlobalStyles /> 컴포넌트, css와 keyframe 헬퍼 등 필수 유틸리티를 포함합니다. 이것이 기본값이며 별도로 설치할 필요가 없습니다.
  • @mui/styled-engine-sc: 비슷한 래퍼지만 styled-components에 특화된 것입니다. styled-components를 Material UI와 함께 사용하려면 이 패키지를 설치하고 구현해야 합니다.

이 두 패키지는 같은 인터페이스를 구현하므로 서로 바꿔 쓸 수 있습니다.

번들러 구성 (Bundler configuration)

기본적으로 @mui/material은 @mui/styled-engine을 의존성으로 갖고 있습니다. styled-components를 사용하려면 번들러를 구성해서 이 의존성을 @mui/styled-engine-sc로 바꿔줘야 합니다.

yarn 사용 시 (With yarn)

yarn을 사용한다면 package resolutions을 이용해 구성할 수 있어요.

 {
   "dependencies": {
-    "@mui/styled-engine": "latest"
+    "@mui/styled-engine": "npm:@mui/styled-engine-sc@latest"
   },
+  "resolutions": {
+    "@mui/styled-engine": "npm:@mui/styled-engine-sc@latest"
+  },
 }

npm 사용 시 (With npm)

npm에는 package resolutions이 없기 때문에, 번들러 설정을 업데이트해서 이 alias를 추가해야 합니다. 아래 예시는 webpack으로 하는 방법을 보여줍니다.

 module.exports = {
   //...
+  resolve: {
+    alias: {
+      '@mui/styled-engine': '@mui/styled-engine-sc'
+    },
+  },
 };

TypeScript라면 아래처럼 tsconfig.json도 업데이트해야 합니다.

 {
   "compilerOptions": {
+    "paths": {
+      "@mui/styled-engine": ["./node_modules/@mui/styled-engine-sc"]
+    }
   },
 }

Next.js

+const withTM = require('next-transpile-modules')([
+  '@mui/material',
+  '@mui/system',
+  '@mui/icons-material', // If @mui/icons-material is being used
+]);

+module.exports = withTM({
 webpack: (config) => {
   config.resolve.alias = {
     ...config.resolve.alias,
+    '@mui/styled-engine': '@mui/styled-engine-sc',
    };
    return config;
  }
+});

:::info 버전 호환성: Material UI 패키지와 같은 메이저 버전의 @mui/styled-engine-sc를 사용하세요. 예를 들어 @mui/[email protected]에는 @mui/[email protected]를 씁니다.

설치되는 styled-components 버전은 @mui/styled-engine-sc의 peer dependency를 충족하기만 하면 됩니다. Material UI v7과 v9에서는 styled-components@^6.0.0입니다. :::

더 알아보기 (Learn more)

  • Material UI 통합 안내