Gatsby - 스타일 로딩이 느린 문제 | Dogma
Gatsby - 스타일 로딩이 느린 문제

스타일이 HTML보다 늦게 로드되는 문제 해결

2022-01-27 작성


페이지 로딩 시, 스타일이 늦게 로드되는 현상이 있었다.

스타일이 없는 날것의 HTML이 먼저 보이고, 잠시 후에 스타일이 씌워지는 현상이 나타난다. 아래 그림과 같다.

화면 기록 2022-01-27 오전 2 49 22

gatsby-plugin-emotion 플러그인을 추가해야 한다고 하여 설치하였으나, 변화가 없었다.

이외에도 gatsby-config.js에 다음과 같이 설정하라는 포스트를 찾아 똑같이 시도해 보았으나, 작동하지 않았다.

{
  resolve: `gatsby-plugin-emotion`,
  options: {
  // Accepts the following options, all of which are defined by `@emotion/babel-plugin` plugin.
  // The values for each key in this example are the defaults the plugin uses.
    sourceMap: true,
    autoLabel: 'dev-only',
    labelFormat: `[local]`,
    cssPropOptimization: true,
  },
}

결국에 찾은 해결책은 바로 @emotion/react의 사용이었다.

이전에는 @emotion/css 를 사용하여, 엘리먼트에 className prop을 이용해 스타일을 씌우고 있었다. 하지만 @emotion/css는 프레임워크와 무관하게 동작하도록 설계된(Framework Agnostic) 패키지였기 때문에, Gatsby와 같은 서버 사이드 렌더링 프레임워크에서는 의도한 대로 동작하지 않았던 것이고 따라서 스타일과 HTML이 별도로 클라이언트에 도착하여, 딜레이가 있었던 것이다.

@emotion/react는 React 프레임워크와 좀더 잘 맞물리도록 만들어진 패키지이고, 리액트를 사용할 경우 이 패키지를 사용할 것을 emotion은 권장하고 있다.

emotion 문서에서는 @emotion/react에 대해 다음과 같이 소개하고 있다.

  • Best when using React with a build environment that can be configured.
  • css prop support
    • Similar to the style prop, but also has support for auto vendor-prefixing, nested selectors, and media queries.
    • Allows developers to skip the styled API abstraction and style components and elements directly.
    • The css prop also accepts a function that is called with your theme as an argument allowing developers easy access to common and customizable values.
    • Reduces boilerplate when composing components and styled with emotion.
  • Server side rendering with zero configuration.
  • Theming works out of the box.
  • ESLint plugins available to ensure proper patterns and configuration are set.

이 중에서 우리가 주목할 것은 바로 강조된 7번째 줄이다. "서버 사이드 렌더링을 별도의 설정 없이 지원한다". 더 알아보니 @emotion/css의 경우 소개글에

Server side rendering requires additional work to set up

라고 적혀 있던 것으로 보아, 필자는 별도의 설정 없이 @emotion/css를 사용했기 때문에 서버 쪽에서 스타일이 제대로 렌더링 되지 않았고 위와 같은 현상이 나타난 것으로 보인다.

참고자료

Emotion과 Gatsby 연동
Emotion introduction

Source on Github