본문으로 바로가기

antd를 사용하기 위해 글로벌하게 css를 설정하려고 했는데 다음과 같은 오류가 나왔다.

 

Global CSS cannot be imported from files other than your Custom <App>. Please move all global CSS imports to pages/_app.js.

Read more: https://err.sh/next.js/css-global

 

 

Why This Error Occurred

 

An attempt to import Global CSS from a file other than pages/_app.js was made.

Global CSS cannot be used in files other than your Custom <App> due to its side-effects and ordering problems.

 

Possible Ways to Fix It

Relocate all Global CSS imports to your pages/_app.js file.

 

 

(https://nextjs.org/docs/advanced-features/custom-app)

다음의 Next의 공식 문서를 더 읽어보았더니

Next.js uses the App component to initialize pages. You can override it and control the page initialization. 
라고 한다. 페이지를 처음 시작할 때 사용하는 컴포넌트(즉, 모든 컴포넌트의 부모 컴포넌트)이니 해당 컴포넌트를 오버라이드하면 원하는 효과를 낼 수 있을 듯합니다.
또, App 컴포넌트를 오버라이딩하기 위해서는 pages/_app.js를 생성하라고 알려주고 있습니다.

 

공식 문서는 App 컴포넌트를 다음과 같이 사용할 수 있다고 알려주고 있다.

 

  • Persisting layout between page changes
  • Keeping state when navigating pages
  • Custom error handling using componentDidCatch
  • Inject additional data into pages
  • Add global CSS

 

이를 이용하여, pages/_app.js 을 생성한 후 next/app의 App을 불러와 상속시켰습니다.

 

보시면, global CSS를 적용하였고(antd css 삽입)

Layout 컴포넌트를 return 함으로써 어느 페이지를 가던간에 Layout을 렌더하도록 만들었습니다.

 

여기서 component는 각 렌더되는 컴포넌트이며, pageProps는 해당 컴포넌트가 가진 props입니다.

예를 들어 index.js를 렌더한다면 index.js의 컴포넌트가 components, 해당 컴포넌트에 부여한 props는 pageProps가 됩니다.

import App from "next/app";
import AppLayout from "../components/AppLayout";
import "antd/dist/antd.css";

class MyApp extends App {
  render() {
    const { Component, pageProps } = this.props;

    return (
      <AppLayout>
        <Component {...pageProps} />
      </AppLayout>
    );
  }
}

export default MyApp;

 

 

함수형 컴포넌트로 전환했습니다. Component는 Next에서 전달해주는 것이므로 그대로 전달해줘야 합니다.

기능은 위와 같습니다.

import AppLayout from "../components/AppLayout";
import Head from "next/head";

import "antd/dist/antd.css";

const MyApp = ({ Component, pageProps }) => {
  return (
    <>
      <Head>
        <title>SNS</title>
      </Head>
      <AppLayout>
        <Component {...pageProps} />
      </AppLayout>
    </>
  );
};

export default MyApp;

 

 

번외)

pages/_app.js와 같이 특수한 역할을 수행하는 페이지들이 있고 이들은 각자 계층적인 구조를 이루고 있습니다.

계층의 순서대로 작성하면 다음과 같습니다.

 

 

pages/_document.js : (https://nextjs.org/docs/advanced-features/custom-document)

 

  html, head. body를 담당합니다.

  일반적으로 title을 수정하려 할 때는 next/head에서 제공하는 Head 컴포넌트를 샀을 텐데

  html을 커스터마이징하기 위해서는 _document.js를 사용하라 합니다.

  If you want to customize the <html>, for example to add the lang attribute, you can do so by creating a pages/_document.js file. 

 

pages/_app.js : (https://nextjs.org/docs/advanced-features/custom-app)

  

  root입니다.

 

pages/우리가 작성한 컴포넌트

 

  실제 컴포넌트

 

pages/_error.js, pages/404.js : (https://nextjs.org/docs/advanced-features/custom-error-page)

 

  에러 발생시 작동하는 컴포넌트


darren, dev blog
블로그 이미지 DarrenKwonDev 님의 블로그
VISITOR 오늘 / 전체