개발이슈

[Next.js] Component selectors can only be used in conjunction 이슈

철스커 2022. 8. 7. 21:55
반응형

create-next-app을 이용해서 새로운 Next.js 프로젝트를 만들고, 개발을 진행했습니다.

프로젝트에서는 Emotion.js를 사용하고 있는데요.

 

 

 

개발을 잘 진행하고 있다가, 다음과 같은 문제가 발생했습니다.

 

 

 

다음과 같은 코드를 보시면, HTML 요소를 스타일링 해줄 때, 다음과 같이 CSS 선택자를 이용하는데요.

...생략

<body>
  <div>
    <p>하이</p>
  </div>
</body>
div p {
  color: red;
  font-weight: bold;
}

 

 

 

 

Component Selector(컴포넌트 선택자)란 상위의 컴포넌트에서 스타일링을 적용을 할 때, 하위의 컴포넌트를 선택해서 스타일링을 하는 것을 의미합니다.

import styled from '@emotion/styled';

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

// 컴포넌트 선택자 사용
const Parent = styled.div`
  ${Child) {
    font-size: 18px;
  }
`;

// 스타일 컴포넌트들을 렌더링
...

render(
  <Parent>
    <Child>
      Child입니다.
    </Child>
  </Parent>
);

 

 

 

 

컴포넌트 선택자를 사용하기 위해서는 기존에는 @emotion/babel-plugin 과 같은 플러그인이 필요했습니다.

 

Emotion – @emotion/babel-plugin

@emotion/babel-plugin is highly recommended, but not required in version 8 and above of Emotion. boolean, defaults to true. Note: Source maps are on by default in @emotion/babel-plugin but they will be removed in production builds 'dev-only' | 'always' | '

emotion.sh

 

 

 

 

그런데 최신 버전의 Next.js는 babel 대신 swc를 이용해서 트랜스파일을 해주는데요.

babel로 트랜스파일을 하지 않는데다가, @emotion/babel-plugin이 없어서 문제가 발생한 것입니다.

 

 

 

 

다음과 같이, next.config.js 파일에 compiler 속성에 emotion: true를 설정하면 문제를 해결할 수 있습니다.

// next.config.js

const nextConfig = {
  ...
  compiler: {
    emotion: true,
  },
};

module.exports = nextConfig;

 

반응형