[React] lighthouse를 이용해 성능 최적화 (code-splitting, lazy-loading)

KBS·2021년 12월 20일
0

React

목록 보기
16/19

프로젝트 적용 결과 미리보기.

lazy-loading 적용 전.

lazy-loading 적용 후.

  • 최초 컨텐츠 풀 페인트 시간이 4.3초에서 0.9초로 단축되었다!
  1. 아래와 같이 lazy로 import한다.

  2. Router로 감싸고, Suspense로 한번더 감싼 후 fallback에 아직 화면이 없을 경우를 구성한다.

APP.js

import React, { Suspense, lazy } from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
------------------------------------------------------

  const MainPage = lazy(() => import("../pages/MainPage"));
  const KakaoRedirect = lazy(() => import("./kakaoRedirect"));
  const GitHubRedirect = lazy(() => import("./GitHubRedirect"));
  const MyPageInfo = lazy(() => import("../components/MyPageInfo"));
  const PostWrite = lazy(() => import("../pages/PostWrite"));
  const PostEdit = lazy(() => import("../pages/PostEdit"));
  const PostDetail = lazy(() => import("../pages/PostDetail"));
  const Markdown = lazy(() => import("../components/Markdown"));
  const Header = lazy(() => import("../components/Header"));
  const Footer = lazy(() => import("../components/Footer"));
  const NotFound = lazy(() => import("../shared/NotFound"));
  
  -------------------------------------------------------------
  <Router>
      <Suspense fallback={<></>}>
      	<ConnectedRouter history={history}>
            <Switch>
              <Route path="/" exact component={MainPage}></Route>
              <Route path="/mypage/:id" exact component={MyPageInfo}></Route>
              <Route path="/postadd" exact component={PostWrite}></Route>
              <Route path="/postedit/:id" exact component={PostEdit}></Route>
              <Route path="/addmarkdown" exact component={Markdown}></Route>
              <Route
                path="/postdetail/:id"
                exact
                component={PostDetail}
              ></Route>
              <Route
                path="/user/kakao/callback"
                exact
                component={KakaoRedirect}
              ></Route>
              <Route
                path="/user/github/callback"
                exact
                component={GitHubRedirect}
              ></Route>
              <Route component={NotFound}></Route>
            </Switch>
          </ConnectedRouter>
   </Suspense>
</Router>
  

참고 사이트: https://kyounghwan01.github.io/blog/React/optimize-performance/code-splitting/#code-splitting-%E1%84%87%E1%85%A1%E1%86%BC%E1%84%87%E1%85%A5%E1%86%B8-2

profile
FE DEVELOPER

0개의 댓글