首页  >  文章  >  web前端  >  从 Create React App 迁移到 Vite:分步指南

从 Create React App 迁移到 Vite:分步指南

王林
王林原创
2024-09-03 12:30:32646浏览

Migrating from Create React App to Vite: A Step-by-Step Guide

作为 React 开发人员,我们一直在寻找改善开发体验和应用程序性能的方法。您可能会考虑的一项重大升级是从 Create React App (CRA) 迁移到 Vite。 Vite 提供更快的构建时间、更快的热模块更换 (HMR) 和更简化的开发体验。在这份综合指南中,我们将逐步介绍将 CRA 项目迁移到 Vite 的过程,包括处理代理服务器和启用 Gzip 压缩。

目录

  1. 为什么迁移到Vite?
  2. 先决条件
  3. 第一步:创建一个新的Vite项目
  4. 第 2 步:移动源代码
  5. 第 3 步:更新 Package.json
  6. 第四步:配置Vite
  7. 第 5 步:更新进口声明
  8. 第6步:处理环境变量
  9. 第 7 步:更新测试配置
  10. 第 8 步:配置代理服务器
  11. 第 9 步:启用 Gzip 压缩
  12. 第 10 步:最终清理
  13. 结论

为什么迁移到Vite?

在我们深入了解迁移过程之前,让我们简要讨论一下您可能想要从 CRA 切换到 Vite 的原因:

  1. 更快的开发服务器启动:Vite使用原生ES模块,这大大减少了启动开发服务器所需的时间。
  2. 更快的热模块替换 (HMR):代码中的更改几乎立即反映在浏览器中。
  3. 提高了构建性能:Vite 的生产构建通常更快,并且包大小更小。
  4. 更灵活的配置:Vite 允许更轻松地自定义构建过程。

先决条件

开始迁移过程之前,请确保您已:

  • Node.js(版本 18+)
  • npm 或 Yarn
  • 要迁移的 Create React App 项目

第1步:创建一个新的Vite项目

首先,我们新建一个Vite项目:

npm create vite@latest my-vite-app -- --template react
cd my-vite-app

此命令使用 React 模板创建一个新的 Vite 项目。我们将使用它作为迁移的基础。

第 2 步:移动源代码

现在,让我们将现有的源代码从 CRA 项目移动到新的 Vite 项目:

  1. 将 CRA 项目中的 src 目录复制到新的 Vite 项目中,替换现有的 src 目录。
  2. 将您可能拥有的任何其他目录(例如 public、assets)复制到 Vite 项目根目录。

第3步:更新Package.json

我们需要更新 package.json 文件以包含 CRA 项目中的所有依赖项:

  1. 将 CRA 项目的 package.json 中的依赖项和 devDependency 复制到新 Vite 项目的 package.json。
  2. 删除 CRA 特定的依赖项,例如反应脚本。
  3. 添加Vite特定脚本:
"scripts": {
  "dev": "vite",
  "build": "vite build",
  "serve": "vite preview",
  "test": "vitest",
  "lint": "eslint src --ext js,jsx --report-unused-disable-directives --max-warnings 0",
  "preview": "vite preview"
}
  1. 安装依赖项:
npm install

第四步:配置Vite

在项目根目录创建一个 vite.config.js 文件:

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

export default defineConfig({
  plugins: [react()],
  resolve: {
    alias: {
      '@': '/src',
    },
  },
  server: {
    port: 3000,
  },
})

此配置设置 React 插件,定义 src 目录的别名,并将开发服务器端口设置为 3000(与 CRA 的默认值匹配)。

第 5 步:更新进口声明

Vite 使用 ES 模块,因此您可能需要更新一些导入语句:

  1. 在不使用 JSX 的文件中,将 import React from 'react' 替换为 import * as React from 'react'。
  2. 更新所有使用 CRA 特定别名(如 src/)的导入以使用新别名 (@/) 或相对路径。

第6步:处理环境变量

Vite 处理环境变量的方式与 CRA 不同:

  1. 重命名 .env 文件以使用 Vite 前缀:.env、.env.local、.env.development、.env.Production。
  2. 更新代码中的环境变量用法:
    • 将 process.env.REACT_APP_* 更改为 import.meta.env.VITE_*
    • 在您的 .env 文件中,将变量从 REACT_APP_* 重命名为 VITE_*

第7步:更新测试配置

如果您将 Jest 与 CRA 一起使用,则需要切换到 Vitest,它与 Vite 集成得更好:

  1. 安装Vitest及相关包:
npm install -D vitest jsdom @testing-library/react @testing-library/jest-dom
  1. 在项目根目录中创建 vitest.config.js 文件:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()],
  test: {
    globals: true,
    environment: 'jsdom',
    setupFiles: './src/setupTests.js',
  },
})
  1. 更新您的测试文件以使用 Vitest 语法(大多数 Jest 测试应该只需进行最少的更改即可工作)。

步骤 8:配置代理服务器

如果您的 CRA 项目使用了代理配置,您需要在 Vite 中进行设置:

  1. Install http-proxy:
npm install -D http-proxy
  1. Update your vite.config.js:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import httpProxy from 'http-proxy'

const proxy = httpProxy.createProxyServer()

export default defineConfig({
  plugins: [react()],
  server: {
    proxy: {
      '/api': {
        target: 'http://localhost:5000',
        changeOrigin: true,
        configure: (proxy, options) => {
          proxy.on('error', (err, req, res) => {
            console.log('proxy error', err)
          })
          proxy.on('proxyReq', (proxyReq, req, res) => {
            console.log('Sending Request to the Target:', req.method, req.url)
          })
          proxy.on('proxyRes', (proxyRes, req, res) => {
            console.log('Received Response from the Target:', proxyRes.statusCode, req.url)
          })
        },
      },
    },
  },
})

This configuration sets up a proxy for /api requests to http://localhost:5000. Adjust the target URL as needed for your backend.

Step 9: Enable Gzip Compression

To enable Gzip compression in Vite:

  1. Install the vite-plugin-compression plugin:
npm install -D vite-plugin-compression
  1. Update your vite.config.js:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import viteCompression from 'vite-plugin-compression'

export default defineConfig({
  plugins: [
    react(),
    viteCompression({
      verbose: true,
      disable: false,
      threshold: 10240,
      algorithm: 'gzip',
      ext: '.gz',
    }),
  ],
  // ... other configurations
})

This setup will generate Gzip-compressed versions of your assets during the build process.

Step 10: Final Cleanup

  1. Remove any CRA-specific files and folders:

    • Delete config-overrides.js if you were using react-app-rewired
    • Remove the eject script from package.json
  2. Update your README.md to reflect the new Vite setup and commands.

  3. Update your CI/CD pipelines to use the new Vite commands (npm run dev, npm run build, etc.).

Conclusion

Migrating from Create React App to Vite can significantly improve your development experience and application performance. While the process involves several steps, the benefits of faster build times, quicker HMR, and more flexible configuration make it a worthwhile endeavor.

Remember to thoroughly test your application after migration to ensure everything works as expected. You may need to make additional adjustments based on your specific project structure and dependencies.

Have you successfully migrated your project from CRA to Vite? Share your experiences and any additional tips in the comments below!

Happy coding!

以上是从 Create React App 迁移到 Vite:分步指南的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn