博客 / 詳情

返回

如何從 create-react-app 遷移到 Vite?

在不斷髮展的 Web 開發領域,對於任何希望提高性能和可維護性的開發人員來説,掌握高效的工具和流程都至關重要。對於許多希望構建現代單頁 React 應用程序的人來説,Vite 已成為 Create React App (CRA) 的自然繼任者。在本綜合指南中,我們將逐步介紹將您的項目從 CRA 遷移到 Vite 的步驟,重點是實用性和易用性。

距離 Vite 推出已經有4年時間,Vite 5.0 版本在23年11月也正式發佈,使用 Rollup 4使得構建性能的幅提升,同時還有一些新的選項可以改善開發服務器性能,在剛發佈的時候就瞭解了它的底層原理和實現方式,但是因為種種原因並沒有敢在正式環境使用它,比如正式環境與開發環境表現不一致,對一些邊緣問題處理存在問題等等,通過 issue 也能反應出來。但是最近工作中的項目越積越大導致開發環境代碼熱更新越來越慢使得我不得不再次考慮把原項目從 CRA 中遷移到 VIte 做一次大膽的嘗試,接下來就看看如何進行遷移吧:

瞭解從 CRA 到 Vite 的轉變

在深入探討實際步驟之前,讓我們先了解一下為什麼這次遷移可以徹底改變您的開發工作流程。CRA 一直是引導 React 應用的首選解決方案,無需配置麻煩。然而,Vite 提供了更快的開發體驗,具有熱模塊替換 (HMR) 和開箱即用的高效構建優化等功能。Vite 更精簡、更現代的方法可以顯著提高開發和生產的性能。

逐步遷移:開啓你的 Vite 之路

安裝 Vite

遷移從安裝 Vite 和 React 相關庫作為開發依賴項開始。在項目的根目錄中運行以下命令:

yarn add vite @vitejs/plugin-react --save-dev

卸載 create-react-app 的依賴:

yarn remove react-scripts

修改 package.json 文件,使用以下新的腳本:

調整 package.json 文件的“scripts”部分以使用 Vite 的命令:

"scripts": {
  "dev": "vite",
  "build": "vite build",
  "serve": "vite preview"
}

將文件擴展名重命名為 .jsx 或 .tsx

Vite 通過顯式擴展名來區分文件。對於 JSX 文件,你應該將它們從 .js 重命名為 .jsx。如果你使用的是 TypeScript,同樣適用,從 .ts 重命名為 .tsx

mv src/App.js src/App.jsx
mv src/index.js src/index.jsx

創建 vite.config.js 文件

vite.config.js在項目的根目錄中創建一個 vite.config.js 文件並補充配置信息以反映你的構建偏好。

touch vite.config.js

這是一個基本配置:

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

export default defineConfig(() => {
  return {
    build: {
      outDir: 'dist',
    },
    plugins: [react()],
  };
});

還可以包含其他配置來滿足特定的項目需求,例如設置路徑別名:

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

export default defineConfig(() => {
  return {
    build: {
      outDir: 'dist',
    },
    plugins: [react()],
    resolve: {
      alias: {
        '@': path.resolve(__dirname, './src'),
        '@common': path.resolve(__dirname, './src/common'),
        '@pages': path.resolve(__dirname, './src/pages')
      }
    }  
  };
});

修改 index.html 文件

把原來 public 目錄下的 index.html 移動到項目根目錄下,並在文件中找到所有的 %PUBLIC_URL% 然後刪除。

- <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
+ <link rel="manifest" href="/manifest.json" />

html 引入 src/index.js

<body>
  <noscript>You need to enable JavaScript to run this app.</noscript>
  <div id="root"></div>
  <script type="module" src="/src/index.tsx"></script>
</body>

額外的配置細節

配置 Vite TS 類型支持

{
  "compilerOptions": {
    "types": ["vite/client"],
  }
}

兼容 TailwindCSS 在 vite 項目中使用

根目錄下創建 postcss.config.js 文件:

module.exports = {
  plugins: [require('tailwindcss'), require('autoprefixer')]
}

安裝 polyfill

很多依賴會使用 node 中的模塊 api導致項目在啓動後會報類似的錯誤:

Cannot read properties of undefined (reading 'prototype')

使用 polyfill 抹平這些不同環境下的差異:

yarn add vite-plugin-node-polyfills

vite.config.js 中配置這個插件:

import { defineConfig } from 'vite'
import { nodePolyfills } from 'vite-plugin-node-polyfills'

export default defineConfig(() => {
  return {
    // 省略其他配置
    plugins: [react(), nodePolyfills()],
  }
})

配置環境變量

如果之前項目中使用 dotenv 來實現環境變量的基本可以廢棄了,Vite 本身支持的環境變量就已經足夠應對基本的需求了,使用 mode 指定環境從而加載對應的env 配置文件獲取對應的變量:

"scripts": {
    "dev": "vite",
    "build:prod": "vite build --mode production",
    "build:stage": "vite build --mode staging",
    "serve": "vite preview"
  },
  1. yarn dev 對應開發環境,它會去加載 .env.development 文件中的信息;
  2. yarn build:stage 對應預發環境,它會去加載 .env.staging文件中的信息;
  3. yarn build:prod 對應正式環境,它會去加載 .env.production文件中的信息;

注意:env 中的變量如果需要客户端可訪問,變量名必須以 VITE_ 開頭,類似與 nextjs 中 NEXT_PUBLIC_:

# .env.development
VITE_APP_ENV=dev

使用 import.meta.env.xxx 獲取對應的變量值:

const env = import.meta.env.VITE_APP_ENV
console.log(env) // dev

在之前的項目中,你很有可能是這樣獲取環境變量的:

const env = process.env.REACT_APP_ENV

並且有很多第三方依賴包中也可能用到這種語法,但是在 Vite 直接寫這個會報錯,為了兼容第三方依賴包不報錯,在 vite.config.js 中補充 define 配置:

import { defineConfig } from 'vite'

export default defineConfig(() => {
  return {
    // 省略其他配置
    define: {
      'process.env': {}
    }
  }
})

配置端口和接口請求代理

vite.config.js 中使用 server 配置:

import { defineConfig } from 'vite'

export default defineConfig(() => {
  return {
    // 省略其他配置
    server: {
      port: 8080,
      proxy: {
        '/api': {
          target: 'https://app-dev.blocksec.com',
          changeOrigin: true,
          secure: false
        }
      }
    }
  }
})

配置 less 預解析

import { defineConfig } from 'vite'

export default defineConfig(() => {
  return {
    // 省略其他配置
    css: {
      preprocessorOptions: {
        less: {
          math: 'always',
          relativeUrls: true,
          javascriptEnabled: true
        }
      }
    }
  }
})

完成遷移

完成上述步驟後,您就可以啓動新的基於 Vite 的 React 應用了。只需運行:

yarn dev

總結

從 CRA 過渡到 Vite 可以為你帶來更快的構建速度、簡化的開發體驗和更高的性能。正如上面所概述的,遷移過程很容易,但可能需要進行調整以適應你的項目的定製化需求,請密切關注官方 Vite 文檔。

user avatar fehaha 頭像 shangxindi 頭像 liujunqi 頭像 huashenjianlingshouhuni 頭像 shellingfordly 頭像 maogexiaodi 頭像 yumiko_5c088de8aa1fe 頭像 zhangfisher 頭像 opentiny 頭像
9 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.