Next.js 프로젝트 ECharts 번들 크기 최적화 하기

Yejin Yang·2024년 4월 8일
0

[TIL]

목록 보기
66/67

개요

프로젝트 내에서 차트 라이브러리로 Echarts 를 사용하고 있습니다.
ECharts는 기능이 풍부하고 유연성이 높지만, 그만큼 번들 사이즈가 클 수 있다는 단점도 있습니다. 프로젝트에서 BarChart와 LineChart만 사용하고 있음에도 불구하고 전체 라이브러리를 로드하여서 불필요한 부분까지 포함되어 애플리케이션의 성능에 영향을 주고 있었습니다.

트리 쉐이킹(tree shaking)

트리 쉐이킹(tree shaking)은 모듈 번들러가 애플리케이션에서 실제로 사용되지 않는 코드를 제거함으로써 최종 번들의 크기를 줄이는 기술입니다.
ECharts의 경우, 특정 차트 유형이나 기능만 필요하다면, 해당 모듈만을 가져와 사용함으로써 전체 라이브러리를 로드할 때보다 훨씬 경량화된 번들을 생성할 수 있습니다.

번들 사이즈 확인하기

Webpack Analyzer 플러그인은 번들의 크기 및 구성이 어떻게 이루어져있는지 시각적으로 보여줍니다. JavaScript 모듈의 크기 정보를 활용하여 큰 종속성을 제거하거나, 코드를 분할하거나, 필요할 때 일부 부분만 로드하여 클라이언트로 전송되는 데이터의 양을 줄일 수 있습니다.

@next/bundle-analyzer 설치

@next/bundle-analyzer 는 JavaScript 모듈의 크기를 관리하는 데 도움이 되는 Next.js용 플러그인입니다.

npm i @next/bundle-analyzer
# or
yarn add @next/bundle-analyzer
# or
pnpm add @next/bundle-analyzer

next.config.js 셋팅

const withBundleAnalyzer = require('@next/bundle-analyzer')({
  enabled: process.env.ANALYZE === 'true',
})
 
/** @type {import('next').NextConfig} */
const nextConfig = {}
 
module.exports = withBundleAnalyzer(nextConfig)

번들 분석 실행 명령어

ANALYZE=true npm run build
# or
ANALYZE=true yarn build
# or
ANALYZE=true pnpm build

명령어를 실행하면 브라우저에서 세 개의 새 탭의 보고서가 열립니다.

echarts-for-react 번들 크기가 parsed된 size 기준으로 1003KB 를 차지하고 있었습니다. 이제 번들크기를 줄여보도록 하겠습니다

ECharts와 트리 쉐이킹 적용 방법

echarts-for-react
페이지에 자세히 번들 크기를 줄이기 위해 수동으로 ECharts.js 모듈 가져오는 방법에 대해서 나와 있습니다.
프로젝트 내에서 필요한 charts와 components등은 공식 문서 보고 import 하면 됩니다.

예시

// import the core library.
import ReactEChartsCore from 'echarts-for-react/lib/core';
// Import the echarts core module, which provides the necessary interfaces for using echarts.
import * as echarts from 'echarts/core';
// Import charts, all with Chart suffix
import {
  // LineChart,
  BarChart} from 'echarts/charts';

// import components, all suffixed with Component
import {
  GridComponent,
  TooltipComponent,
  TitleComponent,
  DatasetComponent,
} from 'echarts/components';

import {
  CanvasRenderer,
  // SVGRenderer,
} from 'echarts/renderers';

echarts.use(
  [TitleComponent, TooltipComponent, GridComponent, BarChart, CanvasRenderer]
);

// The usage of ReactEChartsCore are same with above.
// ReactEChartsCore 컴포넌트에 `echarts={echarts}` 를 꼭 전달해야합니다. 

<ReactEChartsCore
  echarts={echarts}
  option={this.getOption()}
  notMerge={true}
  lazyUpdate={true}
  theme={"theme_name"}
  onChartReady={this.onChartReadyCallback}
  onEvents={EventsDict}
  opts={}
/>
   

적용 결과


Echarts 트리쉐이킹 후 번들 사이즈가 1003KB에서 375KB로 줄었습니다. 약 62%의 사이즈 감소를 했습니다. 단지 라이브러리를 import하는 방법을 변경했을 뿐인데, 이 작은 조정만으로도 번들 사이즈 최적화에 확실한 효과가 있었습니다.

import ReactECharts from 'echarts-for-react';

ECharts와 echarts-for-react 라이브러리를 사용하면서 위와 같은 방식으로 import하고 계시다면, 트리 쉐이킹을 활용하여 번들 사이즈 최적화를 고려해 보시는 것을 추천드립니다.

profile
Frontend developer

0개의 댓글