[React] 빌드 최적화

CHAENG·2024년 7월 25일
0

FrontEnd

목록 보기
10/10

build 진행 시, 용량이 커서 경고가 발생하는 상황이었다.

WARNING in asset size limit: The following asset(s) exceed the recommended size limit (244 KiB).
This can impact web performance.
Assets: 
  main.3cd8f7101a818783d279.js (2.21 MiB)
  705.6afa43ca5311414a0691.js (356 KiB)

WARNING in entrypoint size limit: The following entrypoint(s) combined asset size exceeds the recommended limit (244 KiB). This can impact web performance.
Entrypoints:
  main (2.55 MiB)
      705.6afa43ca5311414a0691.js
      main.3cd8f7101a818783d279.js

해당 문제를 해결하기 위해 여러가지 시도해 볼 수 있는 방법을 정리해보고자 한다.


✅ Lazy Loading 개선

  • 규칙
    • React 컴포넌트 포함
    • default export를 반드시 가져야 함
  • 컴포넌트를 동적으로 로드하고, 필요한 경우에만 로드되도록 설정
    • 초기 다운로드 크기를 줄이고 성능향상 가능
// Lazy-loaded components
const Login = lazy(() => import('/src/pages/Login'));
const Workspace = lazy(() => import('./src/pages/Workspace/Workspace'));
const Test = lazy(() => import('./src/pages/Test'));
const Upload = lazy(() => import('./src/pages/Upload'));
const StandardManagement = lazy(() => import('./src/pages/Workspace/StandardManagement'));
...

✅ Webpack Bundle Analyzer 활용

  • 설치
npm install --save-dev webpack-bundle-analyzer
  • webpack에 불러오기
// Plugin 변수 생성 (Plugin 불러오기)
const BundleAnalyzerPlugin =
  require("webpack-bundle-analyzer").BundleAnalyzerPlugin;

// Plugins 에서 사용하겠다고 명시하기
plugins: [
	   new BundleAnalyzerPlugin({
      analyzerMode: 'static',
      reportFilename: 'bundle-report.html',
      openAnalyzer: false,
      excludeAssets: [/node_modules/],
    }),
			 ...
  ],
  • script 작성
"analyze": "webpack --config webpack.config.js"
  • 결과 → index.css 파일이 가장 큰 것을 파악함

  • optimization.minimizer (실패)
    • css-minimizer-webpack-plugin 설치

    • terser-webpack-plugin 설치

      npm install --save -dev {package}
    • webpack.config.js 파일 내용추가

      optimization: {
          minimize: true,
          minimizer: [
            new CssMinimizerPlugin(),
            new TerserPlugin({
              extractComments: false,
              terserOptions: {
                format: {
                  comments: false,
                },
              },
            }),
          ],
        },
  • tailwind css 공식홈페이지 참고 (Optimizing for Production)
    • @fullhuman/postcss-purgecss, cssnano 설치

    • postcss-cli 설치

      npm install @fullhuman/postcss-purgecss cssnano
      npm install --save-dev postcss-cli    
    • tailwind.config.js 파일 수정
      - purge : 사용하지 않는 스타일을 제거하여 더 작은 CSS 파일을 생성

      purge: ['./src/**/*.{js,jsx,ts,tsx}', './public/index.html'],
    • postcss.config.js 파일 수정
      - purgecss 모듈 : 사용하지 않는 CSS 클래스를 제거하여 최종 CSS 파일의 크기를 줄임
      - plugin 설정
      - tailwindcss : css 스타일 적용
      - autoprefixer : 벤더 프리픽스 자동추가 → 브라우저 호환성 높임
      - @fullhuman/postcss-purgecss : PurgeCSS가 스캔할 파일 경로 지정
      - cssnano : CSS파일을 압축하여 파일 크기를 줄임

      const purgecss = require('@fullhuman/postcss-purgecss');
      
      module.exports = {
        plugins: {
          tailwindcss: {},
          autoprefixer: {},
          '@fullhuman/postcss-purgecss': purgecss({
            content: ['./src/**/*.html', './src/**/*.js', './src/**/*.jsx'],
            defaultExtractor: (content) => content.match(/[\w-/:]+(?<!:)/g) || [],
          }),
          cssnano: {
            preset: 'default',
          },
        },
      };
    • build:css 실행

      "build:css": "postcss ./index.css -o dist/index.css",
    • 결과

      • index.css 파일 크기가 줄어든 것 확인 가능
      • build후 파일 크기 변화
        • main.js 파일 크기 약 2.21MB → Warning 창에서 사라짐 / 약 387KiB 차지


profile
FrontEnd Developer.

0개의 댓글

관련 채용 정보