>  기사  >  웹 프론트엔드  >  Create React App에서 Vite로 마이그레이션: 단계별 가이드

Create React App에서 Vite로 마이그레이션: 단계별 가이드

王林
王林원래의
2024-09-03 12:30:32646검색

Migrating from Create React App to Vite: A Step-by-Step Guide

React 개발자로서 우리는 항상 개발 경험과 애플리케이션 성능을 향상시킬 수 있는 방법을 찾고 있습니다. 고려할 수 있는 중요한 업그레이드 중 하나는 CRA(Create React App)에서 Vite로 마이그레이션하는 것입니다. Vite는 더 빠른 빌드 시간, 더 빠른 HMR(핫 모듈 교체) 및 더욱 간소화된 개발 환경을 제공합니다. 이 종합 가이드에서는 프록시 서버 처리 및 Gzip 압축 활성화를 포함하여 CRA 프로젝트를 Vite로 마이그레이션하는 과정을 안내합니다.

목차

  1. Vite로 마이그레이션해야 하는 이유
  2. 전제조건
  3. 1단계: 새 Vite 프로젝트 만들기
  4. 2단계: 소스 코드 이동
  5. 3단계: Package.json 업데이트
  6. 4단계: Vite 구성
  7. 5단계: 수입 명세서 업데이트
  8. 6단계: 환경 변수 처리
  9. 7단계: 테스트 구성 업데이트
  10. 8단계: 프록시 서버 구성
  11. 9단계: Gzip 압축 활성화
  12. 10단계: 최종 정리
  13. 결론

왜 Vite로 마이그레이션해야 합니까?

마이그레이션 프로세스를 시작하기 전에 CRA에서 Vite로 전환하려는 이유에 대해 간략하게 논의해 보겠습니다.

  1. 빠른 개발 서버 시작: Vite는 기본 ES 모듈을 사용하므로 개발 서버를 시작하는 데 걸리는 시간이 크게 줄어듭니다.
  2. 더 빠른 핫 모듈 교체(HMR): 코드 변경 사항이 브라우저에 거의 즉시 반영됩니다.
  3. 향상된 빌드 성능: Vite의 프로덕션 빌드는 종종 더 빨라지고 번들 크기가 더 작아집니다.
  4. 보다 유연한 구성: Vite를 사용하면 빌드 프로세스를 더 쉽게 사용자 정의할 수 있습니다.

전제 조건

마이그레이션 프로세스를 시작하기 전에 다음 사항을 확인하세요.

  • Node.js(버전 18+)
  • npm 또는 Yarn
  • 마이그레이션하려는 React 앱 프로젝트 생성

1단계: 새 Vite 프로젝트 생성

먼저 새로운 Vite 프로젝트를 만들어 보겠습니다.

npm create vite@latest my-vite-app -- --template react
cd my-vite-app

이 명령은 React 템플릿을 사용하여 새로운 Vite 프로젝트를 생성합니다. 이를 마이그레이션의 기반으로 활용하겠습니다.

2단계: 소스 코드 이동

이제 기존 소스 코드를 CRA 프로젝트에서 새 Vite 프로젝트로 이동해 보겠습니다.

  1. CRA 프로젝트의 src 디렉터리를 새 Vite 프로젝트로 복사하여 기존 src 디렉터리를 바꿉니다.
  2. 보유할 수 있는 추가 디렉토리(예: 공개, 자산)를 Vite 프로젝트 루트에 복사하세요.

3단계: Package.json 업데이트

CRA 프로젝트의 모든 종속성을 포함하도록 package.json 파일을 업데이트해야 합니다.

  1. CRA 프로젝트 package.json의 종속성 및 devDependency를 새 Vite 프로젝트 package.json에 복사합니다.
  2. 반응 스크립트와 같은 CRA 관련 종속성을 제거하세요.
  3. Vite 전용 스크립트 추가:
"scripts": {
  "dev": "vite",
  "build": "vite build",
  "serve": "vite preview",
  "test": "vitest",
  "lint": "eslint src --ext js,jsx --report-unused-disable-directives --max-warnings 0",
  "preview": "vite preview"
}
  1. 종속성 설치:
npm install

4단계: Vite 구성

프로젝트 루트에 vite.config.js 파일을 만듭니다.

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()],
  resolve: {
    alias: {
      '@': '/src',
    },
  },
  server: {
    port: 3000,
  },
})

이 구성은 React 플러그인을 설정하고, src 디렉터리에 대한 별칭을 정의하며, 개발 서버 포트를 3000(CRA 기본값과 일치)으로 설정합니다.

5단계: 가져오기 명세서 업데이트

Vite는 ES 모듈을 사용하므로 일부 import 문을 업데이트해야 할 수도 있습니다.

  1. JSX를 사용하지 않는 파일에서 import React from 'react'를 import * as React from 'react'로 바꾸세요.
  2. CRA 관련 별칭(예: src/)을 사용하는 모든 가져오기를 업데이트하여 새 별칭(@/) 또는 상대 경로를 사용하세요.

6단계: 환경 변수 처리

Vite는 CRA와 다르게 환경 변수를 처리합니다.

  1. Vite 접두사를 사용하도록 .env 파일 이름을 바꿉니다: .env, .env.local, .env.development, .env.production.
  2. 코드에서 환경 변수 사용법을 업데이트하세요.
    • process.env.REACT_APP_*를 import.meta.env.VITE_*로 변경하세요.
    • .env 파일에서 변수 이름을 REACT_APP_*에서 VITE_*로 바꿉니다.

7단계: 테스트 구성 업데이트

CRA와 함께 Jest를 사용하는 경우 Vite와 더 잘 통합되는 Vitest로 전환해야 합니다.

  1. Vitest 및 관련 패키지 설치:
npm install -D vitest jsdom @testing-library/react @testing-library/jest-dom
  1. 프로젝트 루트에 vitest.config.js 파일을 만듭니다.
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()],
  test: {
    globals: true,
    environment: 'jsdom',
    setupFiles: './src/setupTests.js',
  },
})
  1. Vitest 구문을 사용하도록 테스트 파일을 업데이트하세요(대부분의 Jest 테스트는 최소한의 변경으로 작동해야 함).

8단계: 프록시 서버 구성

CRA 프로젝트에서 프록시 구성을 사용한 경우 Vite에서 설정해야 합니다.

  1. Install http-proxy:
npm install -D http-proxy
  1. Update your vite.config.js:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import httpProxy from 'http-proxy'

const proxy = httpProxy.createProxyServer()

export default defineConfig({
  plugins: [react()],
  server: {
    proxy: {
      '/api': {
        target: 'http://localhost:5000',
        changeOrigin: true,
        configure: (proxy, options) => {
          proxy.on('error', (err, req, res) => {
            console.log('proxy error', err)
          })
          proxy.on('proxyReq', (proxyReq, req, res) => {
            console.log('Sending Request to the Target:', req.method, req.url)
          })
          proxy.on('proxyRes', (proxyRes, req, res) => {
            console.log('Received Response from the Target:', proxyRes.statusCode, req.url)
          })
        },
      },
    },
  },
})

This configuration sets up a proxy for /api requests to http://localhost:5000. Adjust the target URL as needed for your backend.

Step 9: Enable Gzip Compression

To enable Gzip compression in Vite:

  1. Install the vite-plugin-compression plugin:
npm install -D vite-plugin-compression
  1. Update your vite.config.js:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import viteCompression from 'vite-plugin-compression'

export default defineConfig({
  plugins: [
    react(),
    viteCompression({
      verbose: true,
      disable: false,
      threshold: 10240,
      algorithm: 'gzip',
      ext: '.gz',
    }),
  ],
  // ... other configurations
})

This setup will generate Gzip-compressed versions of your assets during the build process.

Step 10: Final Cleanup

  1. Remove any CRA-specific files and folders:

    • Delete config-overrides.js if you were using react-app-rewired
    • Remove the eject script from package.json
  2. Update your README.md to reflect the new Vite setup and commands.

  3. Update your CI/CD pipelines to use the new Vite commands (npm run dev, npm run build, etc.).

Conclusion

Migrating from Create React App to Vite can significantly improve your development experience and application performance. While the process involves several steps, the benefits of faster build times, quicker HMR, and more flexible configuration make it a worthwhile endeavor.

Remember to thoroughly test your application after migration to ensure everything works as expected. You may need to make additional adjustments based on your specific project structure and dependencies.

Have you successfully migrated your project from CRA to Vite? Share your experiences and any additional tips in the comments below!

Happy coding!

위 내용은 Create React App에서 Vite로 마이그레이션: 단계별 가이드의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.