프론트엔드/NextJS

Styled-Components 새로고침을 하면 스타일이 적용되지 않는 문제

홍수성찬 2023. 3. 23. 20:55

Styled-Components로 스타일을 적용하고 나서 새로고침을 하면 적용되었던 스타일이 제거되는 문제가 발생한다.

 

이전에는 Babel을 사용한 babel-plugin-styled-components를 설치해서 따로 구현을 해서 처리함으로써 문제를 해결했다면 이제는 Next JS의 Rust Compiler인 SWC가 나옴으로써 next.config.js 파일에서 쉽게 처리할 수 있다.

 

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: false,
  compiler: {
    styledComponents: true,
  },
  async rewrites() {
    return [
      {
        ...
      }
    ]
  }
}

module.exports = nextConfig

위에서 작성한 코드에서 보면 compiler를 추가해서 styledComponents를 true로 설정하면 된다.

compiler: {
    styledComponents: true,
  },

이렇게 처리하면 위에서 발생하는 새로고침할 때, 스타일 적용이 제거되는 문제와 Warning 문제가 해결이 된다.

Next JS의 12버전 이상부터 사용이 가능하며, babel을 사용하지 않고 쉽게 해결할 수 있게 됐다.