Error - next/font" requires SWC although Babel is being used due to a custom babel config being present.

조재일·2023년 4월 21일
0

Error

목록 보기
1/3

문제 발생지

import { createGlobalStyle } from "styled-components";
import reset from "styled-reset";

import { Roboto } from 'next/font/google'

const roboto= Roboto({weight:['300','500','700']})


const GlobalStyle = createGlobalStyle`
  ${reset};
  body{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: ${roboto.style.fontFamily};
  }
`;

export default GlobalStyle;

해당 코드를 수정하고 문제가 발생했다.
next/font를 추가하고 나서 문제가 발생했

에러내용

사용자 지정 바벨 구성이 있기 때문에 바벨을 사용하고 있지만 next/font에는 SWC가 필요합니다
라는 에러가 났다.

SWC란?

자밧스크립트 프로젝트의 컴파일과 번들링 모두에 사용될 수 있는 빌드 툴이다. 웹 컴파일러의 기능을 제공하는 툴이다.

처리 방법

에러 마지막줄에
https://nextjs.org/docs/messages/babel-font-loader-conflict
위와 같은 링크가 나타났다

여기서 왜 에러가 발생했는지 말해주고 있다

내용을 간략하게 말하자면, next/font는 Next.js에서 제공하는 폰트 최적화 기능이다. 즉, nextjs의 컴파일러를 사용해야한다는 의미이다.

하지만, 나는 styled components때문에 bebel셋팅을 커스텀을 했다. 이 뜻은 나는 next.js Compiler를 사용하지 않기로 선택했다는 의미이다.

Next에서는 해결방법을
나의 babel 커스텀을 지우라고 하고 있다.

여기서 생각해야할 것이 있다.
내가 babel설정을 왜 custom했는가?

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

이것은 내가 styled components가 서버사이드 렌더링을 사용할 수 있도록 플러그인을 불러오기위해 커스텀을 했다.

그러면 해당 babel custom을 대체할 수 있는가?
그래서 찾아봤다
https://styled-components.com/docs/advanced#example

styled components 공식홈페이지에 여러가지 방법이 나와있었다.

여기서 babel과 함께쓰는 방법, SWC와 함께쓰는 방법이 나와 있었다. 보기에 Compoiler에 따라서 쓰는 방법이 나뉘는 듯했다.
다시, nextjs는 무슨 Compiler를 사용하는지 찾아봤다
https://nextjs.org/docs/advanced-features/compiler
여기 주소에 들어가면

""The Next.js Compiler, written in Rust using SWC,""

라는 문구가 있다. 그러면 Nextjs는 SWC를 사용하니까 SWC를 사용하는 방법을 사용하면, 문제가 없지 않을까 생각했다.

예시 github에 들어가서 여러가지 찾아보았다.

next.config.js 코드

/** @type {import('next').NextConfig} */

const nextConfig = {
  reactStrictMode: true,
  compiler: {
    styledComponents: true,
  },
}

module.exports = nextConfig

_document.tsx

import Document, { DocumentContext } from 'next/document'
import { ServerStyleSheet } from 'styled-components'

export default class MyDocument extends Document {
  static async getInitialProps(ctx: DocumentContext) {
    const sheet = new ServerStyleSheet()
    const originalRenderPage = ctx.renderPage

    try {
      ctx.renderPage = () =>
        originalRenderPage({
          enhanceApp: (App) => (props) =>
            sheet.collectStyles(<App {...props} />),
        })

      const initialProps = await Document.getInitialProps(ctx)
      return {
        ...initialProps,
        styles: [initialProps.styles, sheet.getStyleElement()],
      }
    } finally {
      sheet.seal()
    }
  }
}

해당 방법대로 진행해보자

해결되었다!
여기서 _document파일을 써본적이 없었고 이것이 무슨 역할을 하는지 알 수 없었다. 한번 여기에 대해서 조사해서 next카테고리에 업로드 해봐야겠다.

profile
주니어 프론트엔드 개발자 입니다

0개의 댓글