React 번들 최적화 - 코드 분할 (Code Splitting)

이춘길·2021년 11월 17일
0

React

목록 보기
2/9
post-thumbnail

목표

  • React Code Splitting 사용 이유
  • React Code Splitting 사용 방법

1. 코드 분할 (Code Splitting)(?)

  • 개발하는 앱이 커지면 번들도 자연스럽게 커진다.
  • main.js가 비대해지면 성능상에 이슈가 생긴다.

그러면, 번들을 나눌 수 있는 방법이 없을까?

  • 코드 분할 (Code Splitting)이 번들을 나누는 기술
    • 런타임에 여러 번들을 동적으로 만들고 불러와서 사용
    • 지연 로딩 (Lazy Loading) : 불러오는 시점 전 까지 객체 초기화 (X)

2. 사용 방법

2-1) import()

1) Babel 플러그인 설치

babel-plugin-syntax-dynamic-import

2) Webpack 설정

  • CRA, NextJS등과 같이 프레임워크에서는 기본적으로 제공해준다
module.exports = {
	entry: {
		main: './src/app.js',
	},
	output: {
	// `filename` provides a template for naming your bundles (remember to use `[name]`)
		filename: '[name].bundle.js',
	// `chunkFilename` provides a template for naming code-split bundles (optional)
		chunkFilename: '[name].bundle.js',
	// `path` is the folder where Webpack will place your bundles
		path: './dist',
	// `publicPath` is where Webpack will load your bundles from (optional)
		publicPath: 'dist/'
	}
};

3) import()

// AS_IS
import { add } from './math';
console.log(add(16, 26));

// TO_BE
import("./math").then(math => {
  console.log(math.add(16, 26));
});

2-2) React.lazy

  • 코드 분할과 더불어 Suspense 기능을 통해 로딩과 에러 관련 기능도 제공
  • 서버 사이드 렌더링 제공 (X)
  • Loadable_Components

1) 대표 예제

import React, { Suspense } from 'react';
import MyErrorBoundary from './MyErrorBoundary';

const OtherComponent = React.lazy(() => import('./OtherComponent'));
const AnotherComponent = React.lazy(() => import('./AnotherComponent'));

const MyComponent = () => (
  <div>
    <MyErrorBoundary>
      <Suspense fallback={<div>Loading...</div>}>
        <section>
          <OtherComponent />
          <AnotherComponent />
        </section>
      </Suspense>
    </MyErrorBoundary>
  </div>
);

2) 라우터는 기본적인 코드 분할 요소

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

const Home = lazy(() => import('./routes/Home'));
const About = lazy(() => import('./routes/About'));

const App = () => (
  <Router>
    <Suspense fallback={<div>Loading...</div>}>
      <Switch>
        <Route exact path="/" component={Home}/>
        <Route path="/about" component={About}/>
      </Switch>
    </Suspense>
  </Router>
);

3) 예외 사항

  • React lazy는 현재 default exports만 지원
  • 이외에 컴포넌트는 Webpack Tree Shaking 을 통해 제외
// ManyComponents.js
export const MyComponent = /* ... */;
export const MyUnusedComponent = /* ... */;

// MyComponent.js
export { MyComponent as default } from "./ManyComponents.js";

// MyApp.js
import React, { lazy } from 'react';
const MyComponent = lazy(() => import("./MyComponent.js"));

출처

React 코드 분할

profile
일지를 꾸준히 작성하자.

0개의 댓글