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
浏览:496

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如有侵犯,请联系[email protected]删除
最新教程 更多>
  • 如何在Python中设置子进程的工作目录?
    如何在Python中设置子进程的工作目录?
    如何在Python中设置子进程的工作目录在Python中,subprocess.Popen()函数允许您在Py​​thon中执行命令子进程。一个常见的要求是指定子进程的工作目录。问题:如何使用 subprocess.Popen() 设置子进程的工作目录? 答案:要指定工作目录,请使用 subproc...
    编程 发布于2024-11-06
  • Pandas 什么时候创建视图而不是副本?
    Pandas 什么时候创建视图而不是副本?
    Pandas 视图与副本生成规则Pandas 在决定 DataFrame 上的切片操作是否产生视图或结果时采用特定规则复制。通过了解这些规则,您可以优化数据操作并避免意外行为。从始终生成副本的操作开始:所有操作,除了那些专门设计用于修改的操作就地 DataFrame,创建副本。只有某些操作支持 in...
    编程 发布于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 的查询生成器进行查询:$user...
    编程 发布于2024-11-06
  • 如何使用 document.write 功能动态包含脚本?
    如何使用 document.write 功能动态包含脚本?
    动态包含具有document.write功能的脚本问题:如何将带有变量src属性的脚本标签动态添加到网页中,特别是如果 src 包含 document.write 函数?背景:通常,在 HTML 头中添加具有特定 src 属性的脚本标记可以无缝工作。但是,当src属性中包含document.writ...
    编程 发布于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”时,就会出现此问题。要实现此目的,您可以利用ar...
    编程 发布于2024-11-06
  • Python 第 00 天
    Python 第 00 天
    今天,我开始了我的个人挑战,#100DaysOfCode。为了这个挑战,我选择学习Python,因为我的目标是成为一名数据分析师。 第 2 章: 变量和字符串 我用来学习 Python 的材料是 Eric Matthes 写的一本名为《Python Crash Course》的书。它对学习非常有帮...
    编程 发布于2024-11-06
  • PDO、准备好的语句或 MySQLi:哪一个最适合您的 PHP 项目?
    PDO、准备好的语句或 MySQLi:哪一个最适合您的 PHP 项目?
    揭秘 PDO、Prepared statements 和 MySQLi在 PHP 数据库交互领域,初学者经常会遇到从遗留 mysql_ 过渡的建议* 函数适用于更现代的选项,如 PDO、准备好的语句或 MySQLi。虽然访问和操作数据库的基本目标仍然存在,但每种技术都提供了独特的优势和细微差别。PD...
    编程 发布于2024-11-06

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3