CRA를 Vite로 마이그레이션 하기

Shim.SeongHo·2023년 8월 22일
0

React

목록 보기
11/11

Vite

아주 빠르다고 소문난 번들러를 적용해보고자 한다.

기대 효과

CI/CD 소요 시간 감소

  • CRA 사용 시 빌드 시간 (약 4997ms 소요)

  • Vite 사용 시 빌드 시간 (약 1320ms 소요)

Vite 사용시 빌드 시간이 약 70%나 감소했다.

마이그레이션

1. Vite 패키지 및 플러그인 설치

npm install -D vite @vitejs/plugin-react vite-plugin-eslint vite-tsconfig-paths vite-plugin-env-compatible
  • vite-plugin-svgr : SVG 그래픽을 리액트 컴포넌트처럼 사용
  • vite-plugin-eslint : ESLint 관련 오류 알려줌
  • vite-tsconfig-paths : tsconfig.json에 정의된 paths 매핑사용
  • vite-plugin-env-compatible : 환경변수가 import.meta.env로 시작하지 않고 REACT_APP 으로 시작쓸 수 있게 해줌
  • vite-plugin-checker : Vite는 타입스크립트의 변환 작업만 수행하고 타입 검사는 하지 않음.
  • 개발 단계에서 미리 lint와 타입 검사를 하기위해 설치

2. 루트 폴더에 vite.config.ts 파일 생성

// /frontend/vite.config.ts
import react from '@vitejs/plugin-react';
import tsconfigPaths from 'vite-tsconfig-paths';
import { defineConfig } from 'vite';
import envCompatible from 'vite-plugin-env-compatible';
import checker from 'vite-plugin-checker';

export default defineConfig({
    plugins: [
        react(),
        tsconfigPaths(),
        checker({ typescript: true, eslint: { lintCommand: 'eslint ./src --ext .ts,.tsx' } }),
        envCompatible({ prefix: 'REACT_APP' }),
    ],
    server: {
        // 기본 포트 설정
        port: 3000,
        // 서버 시작 시 자동으로 브라우저 열기
        open: true,
    },
});

3. index.html 파일을 루트 폴더로 이동한다. 공식 문서

추가적인 번들링 과정 없이 index.html 파일이 앱의 진입점이 되게끔 하기 위함.

4. index.html 파일 수정

  • Vite는 index.html 내에 존재하는 URL에 대해 %PUBLIC_URL%과 같은 Placeholder 없이 사용할 수 있도록 URL 베이스를 자동으로 맞춰주기 때문에 %PUBLIC_URL% 를 삭제
  • <body> 태그 태에 진입점을 추가해준다.
<script type="module" src="/frontend/src/index.tsx"></script>

5. tsconfig.json 수정

{
  "compilerOptions": {
		// ...
    "types": ["vite/client"],
		"isolatedModules": true
  }
}
  • "types": ["vite/client"] : vite는 기본적으로 Node.js API 기반의 타입 시스템을 사용하는데, 클라이언트의 환경을 위해서 필요한 설정 (참고)
  • "isolatedModules": true : esbuild는 타입에 대한 정보 없이 변환만 수행하기 때문에 const enum 또는 암시적으로 타입만을 가져오는 것과 같은 기능을 지원하지 않음
    • 이를 감지하기 위해 해당 설정이 필요함 (참고)

6. build output name 설정 (option)

Vite의 기본 outDir은 dist 로 설정되어 있다.

이를 변경하기 위한 옵션

// vite.config.ts
build: {
    outDir: 'build',
},

7. package.json 수정

"scripts": {
	"start": "vite",
  "build": "vite build",
  "preview": "vite preview --port 8080", // --port 로 포트 번호를 지정할 수 있다.
}

8. node_modules 삭제 후 설치

rm -rf /node_modules

npm install

결과 비교

  • CRA 사용시 CI/CD 소요 시간
  • Vite 번들러 사용시 CI/CD 소요 시간

CI/CD 소요 시간 6분 2초에서 2분 4초로 약 66% 감소 !!

정말 빠른 Vite.

profile
알아가는 재미

0개의 댓글