Emotion 컴포넌트를 일반 CSS 선택자로 사용하기 | Next.js

Bori·2023년 6월 6일
5

Next.js

목록 보기
8/12
post-thumbnail

Targeting another emotion component

Emotion은 styled-components와 비슷하게 emotion 컴포넌트를 CSS 선택자로 사용할 수 있습니다.
단, @emotion/babel-plugin 바벨 플러그인이 필요합니다.

import styled from '@emotion/styled'

const Child = styled.div`
  color: red;
`

const Parent = styled.div`
  // Parent 컴포넌트 내의 Child 컴포넌트의 글꼴 색은 green으로 나타납니다.
  ${Child} {
    color: green;
  }
`

return(
  <div>
    <Parent>
      <Child>Green because I am inside a Parent</Child>
    </Parent>
    <Child>Red because I am not inside a Parent</Child>
  </div>
)

Next.js 프로젝트의 경우 @emotion/babel-plugin을 설치할 필요없이 next.config.jscompiler 속성을 다음과 같이 설정해주면 됩니다.

const nextConfig = {
  ...
  compiler: {
    // emotion 관련 옵션들을 기본값으로 설정
    emotion: true
  },
};

module.exports = nextConfig;

Next.js 12 버전부터 컴파일러를 기존 Babel에서 Rust 기반의 SWC로 변경하였습니다. 따라서, @emotion/babel-plugin을 대신하여 SWC 컴파일러를 사용할 수 있습니다.

SWC(Speedy Web Compiler)란?

  • Rust라는 언어로 제작된 빌드 툴입니다.
  • Next.js에서는 SWC를 기반으로 개발한 컴파일러를 통해 기존 빌드에 활용하던 바벨과 Terser를 대체합니다.
    • 바벨 : 트랜스파일링 수행
    • Terser : 코드 경량화 수행
  • SWC를 사용하여 트랜스파일링은 17배, 코드 경량화 작업은 7배 빨라졌다고 합니다.
  • Rust는 프로그래밍 언어 중 하나로 이벤트 루프 기반의 싱글 스레드 언어인 자바스크립트와 다르게 병렬 처리를 고려하여 설계된 언어입니다.
    ⇒ 병렬 처리가 가능하여 SWC는 의존성이 없는 파일들을 동시에 변환할 수 있어 속도가 빠릅니다.

next.config.js 다음과 같이 emition을 설정할 수 있습니다.

module.exports = {
  compiler: {
    emotion: boolean | {
      // default is true. It will be disabled when build type is production.
      sourceMap?: boolean,
      // default is 'dev-only'.
      autoLabel?: 'never' | 'dev-only' | 'always',
      // default is '[local]'.
      // Allowed values: `[local]` `[filename]` and `[dirname]`
      // This option only works when autoLabel is set to 'dev-only' or 'always'.
      // It allows you to define the format of the resulting label.
      // The format is defined via string where variable parts are enclosed in square brackets [].
      // For example labelFormat: "my-classname--[local]", where [local] will be replaced with the name of the variable the result is assigned to.
      labelFormat?: string,
      // default is undefined.
      // This option allows you to tell the compiler what imports it should
      // look at to determine what it should transform so if you re-export
      // Emotion's exports, you can still use transforms.
      importMap?: {
        [packageName: string]: {
          [exportName: string]: {
            canonicalImport?: [string, string],
            styledBaseImport?: [string, string],
          }
        }
      },
    },
  },
}

참고

0개의 댓글