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

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 import codecs import codecs import codecs 导入 text = codecs.decode('这狗\ u0001f602'.encode('utf-8'),'utf-8') 印刷(文字)#带有...
    编程 发布于2025-06-08
  • Go语言垃圾回收如何处理切片内存?
    Go语言垃圾回收如何处理切片内存?
    Garbage Collection in Go Slices: A Detailed AnalysisIn Go, a slice is a dynamic array that references an underlying array.使用切片时,了解垃圾收集行为至关重要,以避免潜在的内存泄...
    编程 发布于2025-06-08
  • Python高效去除文本中HTML标签方法
    Python高效去除文本中HTML标签方法
    在Python中剥离HTML标签,以获取原始的文本表示Achieving Text-Only Extraction with Python's MLStripperTo streamline the stripping process, the Python standard librar...
    编程 发布于2025-06-08
  • Go web应用何时关闭数据库连接?
    Go web应用何时关闭数据库连接?
    在GO Web Applications中管理数据库连接很少,考虑以下简化的web应用程序代码:出现的问题:何时应在DB连接上调用Close()方法?,该特定方案将自动关闭程序时,该程序将在EXITS EXITS EXITS出现时自动关闭。但是,其他考虑因素可能保证手动处理。选项1:隐式关闭终止数...
    编程 发布于2025-06-08
  • MySQL中如何高效地根据两个条件INSERT或UPDATE行?
    MySQL中如何高效地根据两个条件INSERT或UPDATE行?
    在两个条件下插入或更新或更新 solution:的答案在于mysql的插入中...在重复键更新语法上。如果不存在匹配行或更新现有行,则此功能强大的功能可以通过插入新行来进行有效的数据操作。如果违反了唯一的密钥约束。实现所需的行为,该表必须具有唯一的键定义(在这种情况下为'名称'...
    编程 发布于2025-06-08
  • 查找当前执行JavaScript的脚本元素方法
    查找当前执行JavaScript的脚本元素方法
    如何引用当前执行脚本的脚本元素在某些方案中理解问题在某些方案中,开发人员可能需要将其他脚本动态加载其他脚本。但是,如果Head Element尚未完全渲染,则使用document.getElementsbytagname('head')[0] .appendChild(v)的常规方...
    编程 发布于2025-06-08
  • 为什么不````''{margin:0; }`始终删除CSS中的最高边距?
    为什么不````''{margin:0; }`始终删除CSS中的最高边距?
    在CSS 问题:不正确的代码: 全球范围将所有余量重置为零,如提供的代码所建议的,可能会导致意外的副作用。解决特定的保证金问题是更建议的。 例如,在提供的示例中,将以下代码添加到CSS中,将解决余量问题: body H1 { 保证金顶:-40px; } 此方法更精确,避免了由全局保证金重置引...
    编程 发布于2025-06-08
  • 如何将PANDAS DataFrame列转换为DateTime格式并按日期过滤?
    如何将PANDAS DataFrame列转换为DateTime格式并按日期过滤?
    Transform Pandas DataFrame Column to DateTime FormatScenario:Data within a Pandas DataFrame often exists in various formats, including strings.使用时间数据时...
    编程 发布于2025-06-08
  • 将图片浮动到底部右侧并环绕文字的技巧
    将图片浮动到底部右侧并环绕文字的技巧
    在Web设计中围绕在Web设计中,有时可以将图像浮动到页面右下角,从而使文本围绕它缠绕。这可以在有效地展示图像的同时创建一个吸引人的视觉效果。 css位置在右下角,使用css float and clear properties: img { 浮点:对; ...
    编程 发布于2025-06-08
  • 用户本地时间格式及时区偏移显示指南
    用户本地时间格式及时区偏移显示指南
    在用户的语言环境格式中显示日期/时间,并使用时间偏移在向最终用户展示日期和时间时,以其localzone and格式显示它们至关重要。这确保了不同地理位置的清晰度和无缝用户体验。以下是使用JavaScript实现此目的的方法。方法:推荐方法是处理客户端的Javascript中的日期/时间格式化和时...
    编程 发布于2025-06-08
  • Python中何时用"try"而非"if"检测变量值?
    Python中何时用"try"而非"if"检测变量值?
    使用“ try“ vs.” if”来测试python 在python中的变量值,在某些情况下,您可能需要在处理之前检查变量是否具有值。在使用“如果”或“ try”构建体之间决定。“ if” constructs result = function() 如果结果: 对于结果: ...
    编程 发布于2025-06-08
  • C++20 Consteval函数中模板参数能否依赖于函数参数?
    C++20 Consteval函数中模板参数能否依赖于函数参数?
    [ consteval函数和模板参数依赖于函数参数在C 17中,模板参数不能依赖一个函数参数,因为编译器仍然需要对非contexexpr futcoriations contim at contexpr function进行评估。 compile time。 C 20引入恒定函数,必须在编译时进行...
    编程 发布于2025-06-08
  • 为什么我在Silverlight Linq查询中获得“无法找到查询模式的实现”错误?
    为什么我在Silverlight Linq查询中获得“无法找到查询模式的实现”错误?
    查询模式实现缺失:解决“无法找到”错误在银光应用程序中,尝试使用LINQ建立错误的数据库连接的尝试,无法找到以查询模式的实现。”当省略LINQ名称空间或查询类型缺少IEnumerable 实现时,通常会发生此错误。 解决问题来验证该类型的质量是至关重要的。在此特定实例中,tblpersoon可能需...
    编程 发布于2025-06-08
  • PHP与C++函数重载处理的区别
    PHP与C++函数重载处理的区别
    作为经验丰富的C开发人员脱离谜题,您可能会遇到功能超载的概念。这个概念虽然在C中普遍,但在PHP中构成了独特的挑战。让我们深入研究PHP功能过载的复杂性,并探索其提供的可能性。在PHP中理解php的方法在PHP中,函数超载的概念(如C等语言)不存在。函数签名仅由其名称定义,而与他们的参数列表无关。...
    编程 发布于2025-06-08

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

Copyright© 2022 湘ICP备2022001581号-3