Code Splitting
- 말 그대로 코드 분할하기!
- Code Splitting을 통해, 불필요한 코드 또는 중복되는 코드가 없이 중복되는 사이즈의 코드가 적절한 타이밍에 로드될 수 있도록 한다.
Code Splitting을 하기전에 cra-bundle-analyzer을 사용해보자
📌 cra-bundle-analyzer
Webpack을 통해 bundle 된 파일들이 어떤 코드로 구성되어 있는지 확인 가능
- cra-bundle-analyzer 라이브러리 설치 및 실행 방법
여기서 image-gallery.js는 모달창을 띄우는 모듈인데, 최초 화면이 렌더링될 때, 굳이 모달창은 렌더링을 할 필요가 없으니 이 모듈을 분리해보자
최적화 이전 코드
import React, { useState } from 'react'
import styled from 'styled-components'
import Header from './components/Header'
import InfoTable from './components/InfoTable'
import SurveyChart from './components/SurveyChart'
import Footer from './components/Footer'
import ImageModal from './components/ImageModal'
function App() {
const [showModal, setShowModal] = useState(false)
return (
<div className="App">
<Header />
<InfoTable />
<ButtonModal onClick={() => { setShowModal(true) }}>올림픽 사진 보기</ButtonModal>
<SurveyChart />
<Footer />
{showModal ? <ImageModal closeModal={() => { setShowModal(false) }} /> : null}
</div>
)
}
최적화 코드 ( Code Splitting )
import React, { useState, Suspense, lazy } from 'react'
import styled from 'styled-components'
import Header from './components/Header'
import InfoTable from './components/InfoTable'
import SurveyChart from './components/SurveyChart'
import Footer from './components/Footer'
import ImageModal from './components/ImageModal'
function App() {
const [showModal, setShowModal] = useState(false)
return (
<div className="App">
<Header />
<InfoTable />
<ButtonModal onClick={() => { setShowModal(true) }}>올림픽 사진 보기</ButtonModal>
<SurveyChart />
<Footer />
<Suspense fallback={null}>
{showModal ? <LazyImageModal closeModal={() => { setShowModal(false) }} /> : null}
</Suspense>
</div>
)
}
- lazy는 runtime 중에 우리가 필요한 컴포넌트를 Import를 할 수 있게 해줌
- 실제 로드가 되는 시점은, 정해진 주소로 접속을 했을 때 component를 로드하게 된다.
- Suspense
- 하위 컴포넌트들이 동적으로 로드되다 보니, 어느순간 로드되지 않는 순간이 올 수 있음..
- 이때 fallback 파라미터에 있는 코드를 수행하도록 함
- 컴포넌트가 로드되는 중에 나타나는 메시지를 설정할 수 있음
'Web Performance Optimization' 카테고리의 다른 글
[WPO] 컴포넌트 Preloading (0) | 2022.09.15 |
---|---|
[WPO] 이미지 Preloading (0) | 2022.09.14 |
[WPO] transform을 이용한 애니메이션 최적화 (0) | 2022.09.13 |
[WPO] 브라우저 렌더링 과정 : Critical Rendering Path, Reflow, Repaint (0) | 2022.09.13 |
[WPO] Lighthouse (0) | 2022.09.01 |