CRA 에서 Vite로 마이그레이션

백동우·2025년 3월 5일
post-thumbnail

설명

CRA와 Vite에 차이점

  • Vite는 프런트엔드 프로젝트를 위한 차세대 빌드 도구로, 빠른 개발 서버와 빌드 성능을 제공하는 것이 특징이다. 기본적으로 ES Module(ESM)을 활용한 빠른 HMR(Hot Module Replacement) 및 최적화된 번들링을 지원하며, React, Vue, Svelte 등 다양한 프레임워크에서 사용할 수 있다.

Vite 장점

✅ 빠른 개발 서버 속도 → 필요할 때 필요한 파일만 로드
✅ 빠른 HMR(Hot Module Replacement) → 실시간 코드 반영 속도가 빠름
✅ 빠른 빌드 속도 → esbuild 활용으로 Webpack보다 빠른 번들링
✅ 간편한 설정 → vite.config.ts만 수정하면 쉽게 설정 변경 가능
✅ 최신 JavaScript 생태계 지원 → ESM(ES Module) 지원, 최신 브라우저 최적화
✅ 다양한 플러그인 활용 가능 → Rollup 기반 플러그인 사용

수정사항

명령어

  1. npm uninstall react-scripts
  2. npm install --save-dev vite @vitejs/plugin-react vite-plugin-svgr vite-plugin-env-compatible vite-tsconfig-paths
  • vite-plugin-svgr : SVG를 React 구성 요소로 가져오기 위한 라이브러리
  • vite-plugin-env-compatible : 환경변수가 import.meta.env로 시작하지 않고 REACT_APP 으로 시작쓸 수 있게 해줌 (기존 CRA에서 사용한 환경변수 그대로사용)
  • vite-tsconfig-paths : ESLint가 프로젝트의 모듈 경로를 올바르게 확인 가능. tsconfig.json에서 baseUrl 및 paths 구성을 읽고 ESLint에서 사용가능하도록함

package.json

  • react-script(CRA)
  "scripts": {
    "start": "react-scripts start",
    "start:prod": "npm run build && npx serve -s build",
    "build": "react-scripts build",
    "eject": "react-scripts eject",
    "analyze": "npm run build && source-map-explorer 'build/static/js/*.js'"
  },
  • Vite
  "scripts": {
    "start": "vite",
    "start:prod": "vite build && npx serve -s dist",
    "build": "vite build",
    "eject": "echo 'Eject is not supported with Vite'",
    "analyze": "vite build && source-map-explorer 'dist/assets/*.js'"
  }

vite.config.ts

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import svgr from 'vite-plugin-svgr';
import envCompatible from 'vite-plugin-env-compatible';
import tsconfigPaths from 'vite-tsconfig-paths';

export default defineConfig({
  build: {
    outDir: 'build', // 빌드 파일을 생성할 디렉토리  (Vite default outDir : dist)
  },
  test: {
    environment: 'jsdom',
    globals: true,
  },
  plugins: [
    react(),
    tsconfigPaths(),
    envCompatible({ prefix: 'REACT_APP' }),
    svgr({
      svgrOptions: {
        exportType: 'named',
        ref: true,
        svgo: false,
        titleProp: true,
      },
      include: '**/*.svg',
    }),
  ],
  server: {
    port: 3000,
    watch: {
      followSymlinks: false,
    },
  },
  assetsInclude: ['**/*.svg'],
} );

tsconfig.json

  • 해당 라인 추가
 "compilerOptions": {
    "types": ["vite/client"],
  }

src/svg.d.ts + vite-env.d.ts

src/svg.d.ts

declare module '*.svg' {
  import React from 'react';
  const src: string;
  export const ReactComponent: React.FunctionComponent<
    React.SVGProps<SVGSVGElement>
  >;
  export default src;
}

vite-env.d.ts

/// <reference types="vite/client" />
/// <reference types="vite-plugin-svgr/client" />

기존 import (오류발생)

  • import { ReactComponent as Logo } from 'assets/icon.svg';

수정 후

  • import Logo from "./assets/icon.svg?url";

index.html

  • public폴더에있는 해당파일을 root로 이동

  • Vite는 index.html 내에 존재하는 URL에 대해 %PUBLIC_URL%과 같은 URL 베이스를 자동으로 맞춰주기 때문에 %PUBLIC_URL% 를 삭제

  • 해당라인 추가 "body 태그"안에

	<script type="module" src="/src/index.tsx"></script>

package.json

성능차이

  • CI/CD 시간이 약 60% 속도차이가... 나타났다
    as-is

to-be

0개의 댓글