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
瀏覽:486

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刪除
最新教學 更多>
  • 為開發人員和安全團隊提供主動的 AppSec 持續漏洞管理
    為開發人員和安全團隊提供主動的 AppSec 持續漏洞管理
    现代软件开发环境中哪些日益增长的网络安全风险让 CISO 忙碌? 开发人员和安全团队面临着越来越多的威胁,从复杂的开源和供应商控制的供应链攻击到 AI 生成的代码引入的漏洞,例如提示注入和 GitHub Copilot 的代码安全性差。现代应用程序通常严重依赖开源组件(例如在 npm、PyPI 或 ...
    程式設計 發佈於2024-11-06
  • 如何使用 React 對 MeteorJS 中的 Bootstrap Spacing 實用程式類別進行故障排除?
    如何使用 React 對 MeteorJS 中的 Bootstrap Spacing 實用程式類別進行故障排除?
    在 Bootstrap 中使用間距實用程式類別在 Bootstrap 中,間距實用程式類別可讓您輕鬆控制元素周圍的間距。但是,如果您在使用它們時遇到問題,這裡有一個指南可以幫助您解決。 更新的間距語法(Bootstrap 4 和 5)Bootstrap 4引入了間距實用程式類別的簡化語法:邊距:m{...
    程式設計 發佈於2024-11-06
  • 如何在Python中設定子程序的工作目錄?
    如何在Python中設定子程序的工作目錄?
    如何在Python中設定子程序的工作目錄在Python中,subprocess.Popen()函數允許您在Py thon中執行指令子程序。一個常見的要求是指定子程序的工作目錄。 問題:如何使用 subprocess.Popen() 設定子程序的工作目錄? 答案:要指定工作目錄,請使用 subproc...
    程式設計 發佈於2024-11-06
  • Pandas 什麼時候創建視圖而不是副本?
    Pandas 什麼時候創建視圖而不是副本?
    Pandas 視圖與副本生成規則Pandas 在決定 DataFrame 上的切片操作是否產生視圖或結果時採用特定規則複製。透過了解這些規則,您可以優化資料操作並避免意外行為。 從始終產生副本的操作開始:所有操作,除了那些專門設計用於修改的操作就地 DataFrame,創建副本。 只有某些操作支援 ...
    程式設計 發佈於2024-11-06
  • 使用代理伺服器解鎖地理限制網站
    使用代理伺服器解鎖地理限制網站
    利用代理服务器绕过区域封锁是一种常用且有效的方法。代理服务器作为中介,可以隐藏用户的真实IP地址,使用户的请求看起来像是来自代理服务器的地理位置,从而绕过区域封锁。 使用代理服务器绕过区域封锁的关键步骤:‌‌ 选择合适的代理服务器‌:根据目标区域的网络环境和遮挡情况,选择覆盖该区域的...
    程式設計 發佈於2024-11-06
  • 如何為三角形中的線性漸變鋸齒線建立平滑邊緣?
    如何為三角形中的線性漸變鋸齒線建立平滑邊緣?
    為線性漸變鋸齒線創建平滑邊緣為了設計具有由兩個三角形形成的尖底的響應式圖像,開發人員在三角形線上遇到了意外的鋸齒狀邊緣。為了解決這個問題,我們探索了產生更平滑漸變過渡的策略。 雖然硬停止線性漸變影像中的顏色通常會導致鋸齒狀邊緣,但調整停止點和起始點可以緩解此問題。不要突然從一種顏色變為另一種顏色,而...
    程式設計 發佈於2024-11-06
  • Java 中「static」的魔力:一為所有,一切為一!
    Java 中「static」的魔力:一為所有,一切為一!
    老实说,当我们第一次遇到 static 关键字时,我们都会想:“这是什么魔法?” ?但别担心,我会用一种简单、深入、甚至有点有趣的方式来分解它! 想象一下你正在参加一个聚会?你和你所有的朋友都戴着帽子。但每个人都必须分享一顶帽子。这基本上就是 Java 中 static 关键字的作用!您不必为每个朋...
    程式設計 發佈於2024-11-06
  • 如何在 Laravel Eloquent ORM 中對錶進行別名以增強靈活性和可讀性?
    如何在 Laravel Eloquent ORM 中對錶進行別名以增強靈活性和可讀性?
    Laravel 的Eloquent 查詢中的別名表:超越DB::table在Laravel 的Eloquent ORM 中,您可以使用乾淨的、物件導向的方法與資料庫進行互動。然而,有時您可能會遇到需要更大靈活性的查詢,例如別名表。 挑戰考慮使用 Laravel 的查詢產生器來查詢:$users = ...
    程式設計 發佈於2024-11-06
  • 如何使用 document.write 功能動態包含腳本?
    如何使用 document.write 功能動態包含腳本?
    動態包含具有document.write功能的腳本問題:如何將帶有變數src屬性的腳本標籤動態加入網頁中,特別是如果src 包含document.write 函數? 背景:通常,在 HTML 頭中添加具有特定 src 屬性的腳本標記可以無縫運作。但是,當src屬性中包含document.write程...
    程式設計 發佈於2024-11-06
  • 為什麼我在 Python 中收到「Bad magic number」導入錯誤?
    為什麼我在 Python 中收到「Bad magic number」導入錯誤?
    Bad Magic Number:了解導入錯誤使用 Python 時,遇到「Bad magic number」ImportError 可能會令人沮喪。此錯誤表示 pyc 檔案(Python 腳本的編譯版本)已損壞,這會導致與 Python 解釋器不相容。 瞭解幻數在 UNIX 中-type 系統中,...
    程式設計 發佈於2024-11-06
  • 如何測試 Go 中未匯出的函數?
    如何測試 Go 中未匯出的函數?
    從非測試 Go 檔案中呼叫測試函數在 Go 中,不應從程式碼本身呼叫測試函數。相反,單元測試應該使用 go test 指令執行。 黑白盒測試Go 支援兩種類型的單元測試:黑盒和白盒.黑盒測試測試從包外部匯出的函數,模擬外部包如何與其互動。 白盒測試從包本身內部測試未導出的函數。 Example考慮...
    程式設計 發佈於2024-11-06
  • 如何優化 Matplotlib 繪圖效能以提高速度和效率?
    如何優化 Matplotlib 繪圖效能以提高速度和效率?
    提高 Matplotlib 繪圖效能使用 Matplotlib 繪圖有時會很慢,尤其是在處理複雜或動畫圖形時。了解這種緩慢背後的原因可以幫助您優化程式碼以獲得更快的效能。 瓶頸和 BlittingMatplotlib 繪圖過程的主要瓶頸在於它對所有內容的重繪每次調用Fig.canvas.draw()...
    程式設計 發佈於2024-11-06
  • 面試工具包:陣列 - 滑動視窗。
    面試工具包:陣列 - 滑動視窗。
    一切都与模式有关! 一旦你学会了这些模式,一切都开始变得更容易了!如果你像我一样,你可能不喜欢技术面试,我不怪你——面试可能很艰难。 数组问题是面试中最常见的问题。这些问题通常涉及使用自然数组: const arr = [1, 2, 3, 4, 5]; 还有字符串问题,本质上是字符...
    程式設計 發佈於2024-11-06
  • 字串常數池:為什麼即使文字存在,「new」也會建立一個新的字串物件?
    字串常數池:為什麼即使文字存在,「new」也會建立一個新的字串物件?
    字串常數池:深入檢查Java 中的字串常數池被池化以優化記憶體使用並提高效能。這表示當遇到字串文字時,編譯器會檢查字串常數池中是否存在具有相同值的現有字串物件。如果找到,引用將定向到現有對象,避免建立新對象。 但是,當使用「new」運算子建立新的 String 物件時,會出現混亂,因為這似乎與規則相...
    程式設計 發佈於2024-11-06
  • 如何在 PHP 中使用 array_push() 處理多維數組?
    如何在 PHP 中使用 array_push() 處理多維數組?
    使用PHP 的array_push 添加元素到多維數組使用多維數組可能會令人困惑,特別是在嘗試添加新元素時。當任務是將儲存在 $newdata 中的循環中的資料附加到給定 $md_array 內的子數組「recipe_type」和「cuisine」時,就會出現此問題。 要實現此目的,您可以利用arr...
    程式設計 發佈於2024-11-06

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

Copyright© 2022 湘ICP备2022001581号-3