首頁  >  文章  >  web前端  >  從 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 開發人員,我們一直在尋找改善開發體驗和應用程式效能的方法。您可能會考慮的一項重大升級是從 Create React App (CRA) 遷移到 Vite。 Vite 提供更快的建造時間、更快的熱模組更換 (HMR) 和更簡化的開發體驗。在這份綜合指南中,我們將逐步介紹將 CRA 專案遷移到 Vite 的過程,包括處理代理伺服器和啟用 Gzip 壓縮。

目錄

  1. 為什麼要遷移到Vite?
  2. 先決條件
  3. 第一步:建立一個新的Vite專案
  4. 第 2 步:移動原始碼
  5. 第 3 步:更新 Package.json
  6. 第四步:設定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
  • 要移轉的 Create React App 專案

步驟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. 將您可能擁有的任何其他目錄(例如 public、assets)複製到 Vite 專案根目錄。

步驟3:更新Package.json

我們需要更新 package.json 檔案以包含 CRA 專案中的所有依賴項:

  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

第四步:配置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 模組,因此您可能需要更新一些導入語句:

  1. 在不使用 JSX 的檔案中,將 import React from 'react' 替換為 import * as React from 'react'。
  2. 更新所有使用 CRA 特定別名(如 src/)的匯入以使用新別名 (@/) 或相對路徑。

步驟6:處理環境變數

Vite 處理環境變數的方式與 CRA 不同:

  1. 重新命名 .env 檔案以使用 Vite 前綴:.env、.env.local、.env.development、.env.Production。
  2. 更新程式碼中的環境變數用法:
    • 將 process.env.REACT_APP_* 改為 import.meta.env.VITE_*
    • 在您的 .env 檔案中,將變數從 REACT_APP_* 重新命名為 VITE_*

步驟7:更新測試配置

如果您將 Jest 與 CRA 一起使用,則需要切換到 Vitest,它與 Vite 整合得更好:

  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