[Next.js] Warning: Prop `className` did not match.

sumin·2023년 4월 27일
1

Next.js

목록 보기
5/5

에러 원인

  • Next.js + Ant Design + styled-components를 사용하면서 생긴 오류인데 경고 문구에 적혀있듯이 서버와 클라이언트의 클래스명이 다른 것이 원인이다.
  • Next.js는 처음 화면을 렌더링할 때, SSR로 작동하기 때문에 서버에서 받은 클래스명과 CSR로 클라이언트에서 받은 className이 달라지면서 생기는 오류이다.
  • 이때, className을 일치시켜 주는 것이 바로 babel-plugin-styled-components 이다.

해결 방법

1. 바벨 플러그인 babel-plugin-styled-components 설치

$ npm install babel-plugin-styled-components

2. .babelrc 설정

루트 디렉토리에 .babelrc 파일을 만들고 아래처럼 작성해 주면 된다.

{
  "presets": ["next/babel"],
  "plugins": ["babel-plugin-styled-components"]
}

+) ver 12 이후

SWC(Speedy Web Compiler)란?

  • Rust 언어 기반으로 만들어 졌고, 자바스크립트 프로젝트를 컴파일과 번들러에 사용할 수 있는 빌드 툴
  • 기존 빌드에 사용했던 Babel보다 빠른 컴파일러 기능을 제공한다.
  • Next.js 12 버전부터 SWC 컴파일러가 Babel을 대체하도록 설정되어 있어 CNA(create-next-app)로 프로젝트를 생성하면 빌드 시 자동으로 SWC 컴파일러가 사용된다.

SWC에 Styled-Components 적용

babel 대신 SWC를 사용하기 위해 babel-plugin-styled-components.babelrc 제거 후, next.config.js에 styledComponents를 추가해 주면 오류가 사라지는 것을 볼 수 있다.

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  swcMinify: true, // 코드 경량화
  compiler: {
    styledComponents: true,
  },
};

module.exports = nextConfig;

참고
https://nextjs.org/docs/architecture/nextjs-compiler#styled-components
https://fe-developers.kakaoent.com/2022/220217-learn-babel-terser-swc/
https://styled-components.com/docs/tooling#serverside-rendering

0개의 댓글