首頁 > web前端 > js教程 > 主體

從 Create-React-App 遷移到 Vite:提升舊應用程式的效能

王林
發布: 2024-08-18 07:34:02
原創
649 人瀏覽過

Migrating from Create-React-App to Vite: Boosting Performance in Legacy Applications

我很高興與大家分享,我們在我的工作場所成功從 create-react-app (CRA) 過渡到 Vite! ?

切換並不簡單,但卻是必要的。我們的應用程式變得越來越緩慢,開發人員體驗 (DX) 也在惡化。我發現自己整天都開著筆記型電腦,因為重新啟動應用程式的速度非常慢。如果您刪除了node_modules,重新安裝了它們,並嘗試啟動應用程序,您可能會浪費一個小時來等待所有內容下載並再次啟動。該應用程式通常需要 12-15 分鐘才能啟動,這是一個嚴重的延遲,尤其是在處理緊急錯誤報告時。此外,CRA 已棄用,不再建議用於引導 React 應用程式。

為什麼要Vite?

最初,我考慮使用 Rspack,它被譽為

webpack 的直接替代品,具有更強大的功能和卓越的生產力。

但是,過渡並不像我希望的那樣順利。儘管 Rspack 已接近生產就緒(在撰寫本文時版本為 1.0.0-beta.4),但我決定選擇更成熟且經過實戰檢驗的解決方案:Vite。

遠離 Webpack 和 CRA 讓我對這些工具及其背後的努力有了新的認識。它們簡化了許多開發過程並提供了即用型設定。

我希望有一天我們能夠真正取代 CRA 和 Webpack,這樣我們在切換到 Vite 這樣的工具時就不需要進行大量的文件更改。

如果您不知道 Webpack、Vite 或 Rspack 是什麼,我在上一篇文章中深入探討了 Webpack 及其用途。 Vite 和 Rspack 是更現代的工具,可以完成類似的工作,但更有效率。

我的 Vite 體驗:優點和缺點

在深入探討如何將舊應用程式移轉到 Vite 之前,我想先分享一下我在開發和生產環境中使用 Vite 的短暫經驗中遇到的優缺點。

優點:

  • 更快的啟動:全新安裝後,我們的伺服器啟動時間大大減少。使用 Webpack 時,過去最多需要 30 分鐘;使用 Vite,現在大約需要 8.5 分鐘。隨後的啟動時間從 12-15 分鐘縮短到 1.5 分鐘。雖然這看起來仍然很慢,但考慮到我們專案的複雜性,這是一個勝利。

注意:我正在測試的筆記型電腦相當舊。在規格較好的新機器上,第二次啟動的啟動時間低至 20-30 秒。

  • 更快的建置時間:我們的 GitHub 工作流程建置時間從 12-13 分鐘減少到僅 7 分鐘 — 幾乎一半的時間!這項轉變每天為我們的開發團隊為每位開發人員節省了至少 20 分鐘。

Migrating from Create-React-App to Vite: Boosting Performance in Legacy Applications
使用 Webpack

Migrating from Create-React-App to Vite: Boosting Performance in Legacy Applications
與Vite

缺點:

  • 用於開發和生產的不同捆綁器: Vite 使用 esbuild 進行開發,使用 Rollup 進行生產,這是一個重大痛點。有些頁面在開發中運作良好,但在生產中崩潰了。儘管總體上沒有太多問題,但這種差異需要手動測試和故障排除。

規劃過渡:如何從 CRA 遷移到 Vite

做你的研究:

這是最關鍵的一步。廣泛的研究是必要的。我瀏覽 Reddit,了解其他開發者從 CRA 過渡到 Vite 的經歷。大多數人都認為這個過程很棘手,但值得付出努力。此外,我閱讀了幾篇關於將 CRA 應用程式遷移到 Vite 所需步驟的部落格文章,因為現在沒有關於此主題的官方教學或文件。

制定您的行動計畫:

  • 將 .js 檔案轉換為 .jsx: 這是一個令人驚訝的挑戰,因為 Vite 不像 Webpack 那樣支援 .js 檔案。手動將所有 .js 檔案轉換為 .jsx 是不可能的,但幸運的是,我找到了一個可以自動化該過程的 CLI 工具。
  • 刪除 react-script,安裝 vite,建立 vite.config.js: 確保您使用的 Vite 版本與您的 Node.js 版本相容。之後,刪除react-scripts,安裝vite,並建立vite.config.js檔案。
yarn remove react-scripts
yarn add vite @vitejs/plugin-react --dev
登入後複製

並在專案根目錄

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

export default defineConfig({
    plugins: [react()],
    build: { // to output your build into build dir the same as Webpack
        outDir: 'build',
    },
    server: {
        open: true,
        port: 3000,
    },
});
登入後複製
  • index.html 移到專案根目錄,將字型移到公用目錄,然後對應更新字型的參考路徑。
  • index.html 中的連結中刪除 %PUBLIC_URL%。
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" /> ❌ 
<link rel="icon" href="/favicon.ico" /> ✅
登入後複製
  • index.html 中加入指向項目入口點的腳本
<body>
  <noscript>You need to enable JavaScript to run this app.</noscript>
  <div id="root"></div>

  <script type="module" src="/src/index.jsx"></script>
</body>
登入後複製
  • 替換環境變數: 在 .env 中將 REACT_APP 替換為 VITE,在程式碼中將 process.env.NODE_ENV 更新為 import.meta.env.MODE,將 process.env.REACT_APP 更新為 import.meta.env.VITE。
  • 配置 eslint: 安裝 vite-plugin-eslint 並更新 vite.config.js 以包含該插件。
yarn add vite-plugin-eslint --dev
登入後複製
import react from '@vitejs/plugin-react';
import { defineConfig } from 'vite';
import eslintPlugin from 'vite-plugin-eslint';

export default defineConfig({
    plugins: [react(), eslintPlugin()],
    build: {
        outDir: 'build',
    },
    server: {
        open: true,
        port: 3000,
    },
});
登入後複製
  • 重新驗證您的 GitHub 工作流程: 更新引用react-scripts的所有工作流程步驟以使用vite。

修正環境特定問題:

  1. 更改所有 需要影像來模組導入。
  • 問題: 在 CRA 中,映像通常使用 require 語句加載,這不適用於 Vite。
  • 解決方案: 將 require 替換為 ES 模組導入。例如:
<img src={require('assets/images/logo.svg')}/> ❌
登入後複製
import Logo from 'assets/images/logo.svg'; 

<img src={Logo}/> ✅
登入後複製

2。解 全域這個沒有定義。

  • 問題: Vite 不會自動提供 globalThis,如果你的程式碼依賴它,這可能會導致問題,Webpack 正在為我們填充它。

Migrating from Create-React-App to Vite: Boosting Performance in Legacy Applications
Webpack 應用程式中的全域變數「globalThis」

  • 解決方案: 在您的 index.jsx 檔案中加入 globalThis 的手動定義
window.global ||= window;
// just double checked my code and I'm a bit skeptical of why I'm not using
// `window.globalThis`and why my code is working with `window.global` ?
登入後複製

3。產生用於錯誤監控的來源對映。

  • 問題: 預設情況下,Vite 可能不會產生來源映射,而來源映射對於使用錯誤監控工具進行偵錯時至關重要。
  • 解決方案: 在 vi​​te.config.js 中啟用來源對應:
import react from '@vitejs/plugin-react';
import { defineConfig } from 'vite';
import eslintPlugin from 'vite-plugin-eslint';

export default defineConfig({
    plugins: [react(), eslintPlugin()],
    build: {
        outDir: 'build',
        sourcemap: true,
    },
    server: {
        open: true,
        port: 3000,
    },
});
登入後複製

4。修復全域 SASS 變數。

  • 問題: Vite 可能無法像 CRA 那樣處理使用 :export 定義的全域 SASS 變數。
  • 解決方案: 將全域 SASS 變數移至 JavaScript 檔案。例如:
//theme.scss ❌

:export { 
    primaryColor: $app-primary;
    secondaryColor: $secondary;
     ....
}

import theme from '../styles/theme.scss';

<div style={{ color: theme.primaryColor }}>Hello World</div>
登入後複製

將被
取代

// theme.js ✅

const theme = { 
    primaryColor: '#10142a',
    secondaryColor: '#2695a2',
    .....
}

export default theme;

import theme from '../styles/theme.js';

<div style={{ color: theme.primaryColor }}>Hello World</div>
登入後複製

5。處理 .jsx 檔案的絕對導入。

  • 問題:絕對導入在 Vite 中可能無法正常運作。
  • 解決方案: 在 vi​​​​te.config.js 中設定別名:
import react from '@vitejs/plugin-react';
import { defineConfig } from 'vite';
import eslintPlugin from 'vite-plugin-eslint';

export default defineConfig({
    plugins: [react(), eslintPlugin()],
    build: {
        outDir: 'build',
        sourcemap: true,
    },
    resolve: {
        alias: [
            { find: 'actions', replacement: '/src/actions' },
            { find: 'assets', replacement: '/src/assets' },
            { find: 'components', replacement: '/src/components' },
            .....
            { find: 'styles', replacement: '/src/styles' }, 
        ],
    },
    server: {
        open: true,
        port: 3000,
    },
});
登入後複製

6。處理 **.scss 檔案的絕對導入。 **

  • 問題: Vite 可能無法在生產環境中正確解析SCSS 檔案的絕對導入,例如,下面的程式碼導入了一個名為app.[hash].js 的檔案(不是我建置的一部分)生產中的app.[hash].css
import MyComponent from 'components/MyComponent';
import styles from 'styles/app.scss';

<MyComponent className={styles.someClassName} />
登入後複製
  • 解決方案:我嘗試回退到檔案的相對路徑,但它不起作用? ‍♂️,我選擇全域導入 SCSS 文件,因為這些類別是透過應用程式共享的
// index.jsx
import React from 'react';
import { render } from 'react-dom';
import Main from './pages/Main';

// Import SCSS globally
import './global.scss';

render(<Main/>, document.querySelector('#root'));

// global.scss

.class1{...}
.class2{...}

...

// cut & paste classes from styles/app.scss here 
// then drop that cursed file
登入後複製

然後我會像普通 CSS 一樣使用它們

<MyComponent className='someClassName' />
登入後複製

7。解決第三方函式庫問題。

  • 問題:某些函式庫可能與Vite不完全相容。
  • 解決方案:更新或取代不相容的函式庫。就我而言,我需要:  — 將 jsonwebtoken 替換為 jsonwebtoken-esm  — 用react-toastify替換react-notifications  — 使用lodash-es代替lodash  — 將react-bootstrap-sweetalert和recharts等函式庫更新到最新版本

結論

從 create-react-app 過渡到 Vite 是一次充滿挑戰但有益的經驗。僅性能的改進就足以讓這些努力變得值得,我相信這將顯著提高開發人員的工作效率和整體專案的可維護性。透過仔細解決這些問題,您可以充分利用 Vite 的現代化工具並提高開發工作流程的效率。

以上是從 Create-React-App 遷移到 Vite:提升舊應用程式的效能的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!