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,    },});

Fix Environment-Specific Issues:

  1. Change all require images to module imports.
\\\"從
import Logo from \\'assets/images/logo.svg\\'; \\\"從

2. Resolve globalThis is not defined.

\\\"Migrating
global variable “globalThis” in a Webpack application

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. Generate source maps for error monitoring.

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. Fix global SASS variables.

//theme.scss ❌:export {     primaryColor: $app-primary;    secondaryColor: $secondary;     ....}import theme from \\'../styles/theme.scss\\';
Hello World

Will be replaced by

// theme.js ✅const theme = {     primaryColor: \\'#10142a\\',    secondaryColor: \\'#2695a2\\',    .....}export default theme;import theme from \\'../styles/theme.js\\';
Hello World

5. Handle absolute imports for .jsx files.

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. Handle absolute imports for **.scss files.**

import MyComponent from \\'components/MyComponent\\';import styles from \\'styles/app.scss\\';
// index.jsximport React from \\'react\\';import { render } from \\'react-dom\\';import Main from \\'./pages/Main\\';// Import SCSS globallyimport \\'./global.scss\\';render(
, document.querySelector(\\'#root\\'));// global.scss.class1{...}.class2{...}...// cut & paste classes from styles/app.scss here // then drop that cursed file

then I’d use them like vanilla CSS

7. Address third-party library issues.

Conclusion

Transitioning from create-react-app to Vite has been a challenging but rewarding experience. The performance improvements alone have made the effort worthwhile, and I believe this will significantly boost both developer productivity and overall project maintainability. By carefully addressing these issues, you can make the most of Vite’s modern tooling and improve the efficiency of your development workflow.

","image":"http://www.luping.net/uploads/20240818/172396369266c1992cc0257.jpg","datePublished":"2024-08-18T14:48:12+08:00","dateModified":"2024-08-18T14:48:12+08:00","author":{"@type":"Person","name":"luping.net","url":"https://www.luping.net/articlelist/0_1.html"}}
」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 從 Create-React-App 遷移到 Vite:提升舊應用程式的效能

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

發佈於2024-08-18
瀏覽:769

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

I'm excited to share that we are successfully transitioning from create-react-app (CRA) to Vite in my workplace! ?

Switching wasn’t straightforward, but it was necessary. Our app was becoming increasingly sluggish, and the developer experience (DX) was deteriorating. I found myself leaving my laptop on all day because restarting the app was painfully slow. If you ever removed node_modules, reinstalled them, and attempted to start the app, you could lose an hour just waiting for everything to download and start up again. The app would usually take 12-15 minutes to start—a significant delay, especially when dealing with urgent bug reports. Additionally, CRA is deprecated and is no longer recommended for bootstrapping React applications.

Why Vite?

Initially, I considered using Rspack, which is touted as

A drop-in replacement for webpack, with more powerful features and exceptional productivity.

However, the transition wasn’t as seamless as I had hoped. Although Rspack is nearing production readiness (at version 1.0.0-beta.4 as of this writing), I decided to opt for the more mature and battle-tested solution: Vite.

Moving away from Webpack and CRA gave me a newfound appreciation for these tools and the effort behind them. They simplify so much of the development process and provide a ready-to-use setup.

I hope that one day we’ll have a true drop-in replacement for CRA and Webpack, so we won’t need to make extensive file changes when switching to tools like Vite.

If you have no idea what Webpack, Vite, or Rspack are, I went down this rabbit hole in my last post, I explored Webpack and what it does. Vite and Rspack are more modern tools doing a similar job but more efficient.

My Experience with Vite: Pros and Cons

Before diving into how I transitioned our old app to Vite, I'd like to share the pros and cons I've encountered during my brief experience using Vite in development and production environment.

Pros:

  • Faster Startup: After a fresh install, our server startup time was drastically reduced. With Webpack, it used to take up to 30 minutes; with Vite, it now takes about 8.5 minutes. Subsequent startups went from 12-15 minutes to just 1.5 minutes. While this might still seem slow, it's a win considering the complexity of our project.

Note: The laptop I’m testing on is quite old. On a newer machine with better specs, startup times were as low as 20–30 seconds for the second start.

  • Faster Build Time: Our GitHub workflow build time decreased from 12–13 minutes to just 7 minutes — almost half the time! This transition saves our development team at least 20 minutes per developer each day.

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

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

Cons:

  • Different Bundlers for Development and Production: Vite uses esbuild for development and Rollup for production, which has been a significant pain point. Some pages worked perfectly in development but crashed in production. This discrepancy required manual testing and troubleshooting, though there weren't many issues overall.

Planning the Transition: How to Migrate from CRA to Vite

Do Your Research:

This is the most crucial step. Extensive research is essential. I browsed Reddit to read about other developers’ experiences transitioning from CRA to Vite. Most agreed that the process is tricky but worth the effort. Additionally, I read several blog posts on the steps needed to move a CRA app to Vite, as there is no official tutorial or documentation on this topic now.

Build Your Action Plan:

  • Convert .js files to .jsx: This was a surprising challenge, as Vite doesn't support .js files as Webpack does. Manually converting all .js files to .jsx was out of the question, but luckily, I found a CLI tool that automated the process.
  • Remove react-script, install vite, create vite.config.js: Ensure you're using a Vite version compatible with your Node.js version. After that, remove react-scripts, install vite, and create the vite.config.js file.
yarn remove react-scripts
yarn add vite @vitejs/plugin-react --dev

and in the project root

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,
    },
});
  • Move index.html to the project root and fonts to the public directory then update reference paths to the fonts accordingly.
  • Remove %PUBLIC_URL% from links in index.html.
  • Add Script pointing at your project entry point in index.html
  
  
  • Replace environment variables: Replace REACT_APP with VITE in .env , update process.env.NODE_ENV with import.meta.env.MODE and process.env.REACT_APP with import.meta.env.VITE in your code.
  • Configure eslint: Install vite-plugin-eslint and update vite.config.js to include the plugin.
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,
    },
});
  • Revalidate your GitHub workflows: Update any workflow steps that reference react-scripts to use vite.

Fix Environment-Specific Issues:

  1. Change all require images to module imports.
  • Issue: In CRA, images were commonly loaded using require statements, which won’t work with Vite.
  • Solution: Replace require with ES module imports. For instance:
從 Create-React-App 遷移到 Vite:提升舊應用程式的效能
import Logo from 'assets/images/logo.svg'; 

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

2. Resolve globalThis is not defined.

  • Issue: Vite doesn’t automatically provide globalThis, which can cause issues if your code relies on it, Webpack was polyfilling it for us.

Migrating from Create-React-App to Vite: Boosting Performance in Legacy Applications
global variable “globalThis” in a Webpack application

  • Solution: Add a manual definition for globalThis in your index.jsx file
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. Generate source maps for error monitoring.

  • Issue: By default, Vite may not generate source maps, which are essential for debugging when you use an error monitoring tool.
  • Solution: Enable source maps in your vite.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. Fix global SASS variables.

  • Issue: Vite may not handle global SASS variables defined with :export as CRA does.
  • Solution: Move global SASS variables to a JavaScript file. For example:
//theme.scss ❌

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

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

Hello World

Will be replaced by

// theme.js ✅

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

export default theme;

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

Hello World

5. Handle absolute imports for .jsx files.

  • Issue: Absolute imports might not work properly in Vite.
  • Solution: Configure aliases in vite.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. Handle absolute imports for **.scss files.**

  • Issue: Vite might not resolve absolute imports for SCSS files correctly in the production environment, for example, The code below was importing a file called app.[hash].js (not a part of my build) instead of app.[hash].css in production
import MyComponent from 'components/MyComponent';
import styles from 'styles/app.scss';


  • Solution: I tried falling back to the relative path of the file but it didn’t work ?‍♂️, I opted into import SCSS files globally since these classes were shared through the application
// index.jsx
import React from 'react';
import { render } from 'react-dom';
import Main from './pages/Main';

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

render(
, document.querySelector('#root')); // global.scss .class1{...} .class2{...} ... // cut & paste classes from styles/app.scss here // then drop that cursed file

then I’d use them like vanilla CSS


7. Address third-party library issues.

  • Issue: Some libraries may not be fully compatible with Vite.
  • Solution: Update or replace incompatible libraries. In my case, I needed to:  — Replace jsonwebtoken with jsonwebtoken-esm  — Replace react-notifications with react-toastify  — Use lodash-es instead of lodash  — Update libraries like react-bootstrap-sweetalert and recharts to their latest versions

Conclusion

Transitioning from create-react-app to Vite has been a challenging but rewarding experience. The performance improvements alone have made the effort worthwhile, and I believe this will significantly boost both developer productivity and overall project maintainability. By carefully addressing these issues, you can make the most of Vite’s modern tooling and improve the efficiency of your development workflow.

版本聲明 本文轉載於:https://dev.to/mazenadel19/migrating-from-create-react-app-to-vite-boosting-performance-in-legacy-applications-1pce?1如有侵犯,請聯絡study_golang@163 .com刪除
最新教學 更多>
  • 如何修復\“常規錯誤:2006 MySQL Server在插入數據時已經消失\”?
    如何修復\“常規錯誤:2006 MySQL Server在插入數據時已經消失\”?
    How to Resolve "General error: 2006 MySQL server has gone away" While Inserting RecordsIntroduction: connect to to to Database connect to t...
    程式設計 發佈於2025-02-19
  • 如何限制動態大小的父元素中元素的滾動範圍?
    如何限制動態大小的父元素中元素的滾動範圍?
    在交互式界面中實現垂直滾動元素的CSS高度限制 考慮一個佈局,其中我們具有與可滾動的映射div一起移動的subollable map div用戶的垂直滾動,同時保持其與固定側邊欄的對齊方式。但是,地圖的滾動無限期擴展,超過了視口的高度,阻止用戶訪問頁面頁腳。 可以限制地圖的滾動,我們可以利用CS...
    程式設計 發佈於2025-02-19
  • 為什麼使用Firefox後退按鈕時JavaScript執行停止?
    為什麼使用Firefox後退按鈕時JavaScript執行停止?
    導航歷史記錄問題:JavaScript使用Firefox Back Back 此行為是由瀏覽器緩存JavaScript資源引起的。要解決此問題並確保在後續頁面訪問中執行腳本,Firefox用戶應設置一個空功能以在window.onunload事件上調用。 pre> window.onload...
    程式設計 發佈於2025-02-19
  • 在保持其內容完整時,如何刪除DIV元素?
    在保持其內容完整時,如何刪除DIV元素?
    在保留其元素 display:cottents;在這種情況下是理想的選擇。它導致元素的孩子出現為父母的直接子女,無視元素本身。當使用CSS網格或其他應該忽略包裝元素的佈局技術時,這是有價值的。 。容器{ 顯示:Flex; } 。一 { 顯示:內容; } 。一個P:第一子女{ 訂單:...
    程式設計 發佈於2025-02-19
  • 如何在Java列表中有效計算元素的發生?
    如何在Java列表中有效計算元素的發生?
    計數列表中的元素出現在列表 中,在java編程中,列舉列表中列舉元素出現的任務來自列表。為此,收集框架提供了全面的工具套件。 在這種情況下,Batocurrences變量將保持值3,代表動物列表中的“ BAT”出現的數量。 &&& [此方法是簡單的,可以得出準確的結果,使其成為計算列表中元素出現的...
    程式設計 發佈於2025-02-19
  • 可以在純CS中將多個粘性元素彼此堆疊在一起嗎?
    可以在純CS中將多個粘性元素彼此堆疊在一起嗎?
    https://webthemez.com/demo/sticky-multi-header-scroll/index.html </main> <section> display:grid; grid-template-col...
    程式設計 發佈於2025-02-19
  • 如何使用替換指令在GO MOD中解析模塊路徑差異?
    如何使用替換指令在GO MOD中解析模塊路徑差異?
    克服go mod中的模塊路徑差異 github.com/coreos/etcd/integration imports :解析GO.mod:模塊將其路徑聲明為: go.etcd.io/bbolt [&&&&&&&&&&&&&&&&&&&&&&&&&&&& github.com/coreos/b...
    程式設計 發佈於2025-02-19
  • 為什麼PYTZ最初顯示出意外的時區偏移?
    為什麼PYTZ最初顯示出意外的時區偏移?
    與pytz 最初從pytz獲得特定的偏移。例如,亞洲/hong_kong最初顯示一個七個小時37分鐘的偏移: 差異源 考慮以下代碼: < pre> import pytz [&& &&&&&&華&& && && && &&&華dt2 = hk.localize(dateTime(2012,1...
    程式設計 發佈於2025-02-19
  • 如何使用Python的記錄模塊實現自定義處理?
    如何使用Python的記錄模塊實現自定義處理?
    使用Python的Loggging Module 確保正確處理和登錄對於疑慮和維護的穩定性至關重要Python應用程序。儘管手動捕獲和記錄異常是一種可行的方法,但它可能乏味且容易出錯。 解決此問題,Python允許您覆蓋默認的異常處理機制,並將其重定向為登錄模塊。這提供了一種方便而係統的方法來捕獲...
    程式設計 發佈於2025-02-19
  • 如何使用PHP從XML文件中有效地檢索屬性值?
    如何使用PHP從XML文件中有效地檢索屬性值?
    從php 您的目標可能是檢索“ varnum”屬性值,其中提取數據的傳統方法可能會使您留下PHP陷入困境。 使用simplexmlelement :: attributes()函數提供了簡單的解決方案。此函數可訪問對XML元素作為關聯數組的屬性: - > attributes()為$ att...
    程式設計 發佈於2025-02-19
  • Java是否允許多種返回類型:仔細研究通用方法?
    Java是否允許多種返回類型:仔細研究通用方法?
    在java中的多個返回類型:一個誤解介紹,其中foo是自定義類。該方法聲明似乎擁有兩種返回類型:列表和E。但是,情況確實如此嗎? 通用方法:拆開神秘 [方法僅具有單一的返回類型。相反,它採用機制,如鑽石符號“ ”。 分解方法簽名: :本節定義了一個通用類型參數,E。它表示該方法接受擴展FOO類的...
    程式設計 發佈於2025-02-19
  • 如何克服PHP的功能重新定義限制?
    如何克服PHP的功能重新定義限制?
    克服PHP的函數重新定義限制在PHP中,多次定義一個相同名稱的函數是一個no-no。嘗試這樣做,如提供的代碼段所示,將導致可怕的“不能重新列出”錯誤。 // error:“ coss redeclare foo()” 但是,php工具腰帶中有一個隱藏的寶石:runkit擴展。它使您能夠靈活...
    程式設計 發佈於2025-02-19
  • 如何在JavaScript對像中動態設置鍵?
    如何在JavaScript對像中動態設置鍵?
    如何為JavaScript對像變量創建動態鍵,嘗試為JavaScript對象創建動態鍵,使用此Syntax jsObj['key' i] = 'example' 1;將不起作用。正確的方法採用方括號:他們維持一個長度屬性,該屬性反映了數字屬性(索引)和一個數字屬性的數量。標準對像沒有模仿這...
    程式設計 發佈於2025-02-19
  • 如何為PostgreSQL中的每個唯一標識符有效地檢索最後一行?
    如何為PostgreSQL中的每個唯一標識符有效地檢索最後一行?
    [2最後一行與數據集中的每個不同標識符關聯。考慮以下數據: 1 2014-02-01 kjkj 1 2014-03-11 ajskj 3 2014-02-01 sfdg 3 2014-06-12 fdsa 為了檢索數據集中每個唯一ID的最後一行信息,您可以在操作員上使用Postgres的有效效...
    程式設計 發佈於2025-02-19

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3