DEV Community

Manoj Swami
Manoj Swami

Posted on

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

As React developers, we're always looking for ways to improve our development experience and application performance. One significant upgrade you might consider is migrating from Create React App (CRA) to Vite. Vite offers faster build times, quicker hot module replacement (HMR), and a more streamlined development experience. In this comprehensive guide, we'll walk through the process of migrating your CRA project to Vite, including handling proxy servers and enabling Gzip compression.

Table of Contents

  1. Why Migrate to Vite?
  2. Prerequisites
  3. Step 1: Create a New Vite Project
  4. Step 2: Move Your Source Code
  5. Step 3: Update Package.json
  6. Step 4: Configure Vite
  7. Step 5: Update Import Statements
  8. Step 6: Handle Environment Variables
  9. Step 7: Update Test Configuration
  10. Step 8: Configure the Proxy Server
  11. Step 9: Enable Gzip Compression
  12. Step 10: Final Cleanup
  13. Conclusion

Why Migrate to Vite?

Before we dive into the migration process, let's briefly discuss why you might want to switch from CRA to Vite:

  1. Faster development server startup: Vite uses native ES modules, which significantly reduces the time it takes to start your development server.
  2. Quicker hot module replacement (HMR): Changes in your code are reflected almost instantly in the browser.
  3. Improved build performance: Vite's production builds are often faster and result in smaller bundle sizes.
  4. More flexible configuration: Vite allows for easier customization of your build process.

Prerequisites

Before starting the migration process, ensure you have:

  • Node.js (version 18+)
  • npm or Yarn
  • A Create React App project you want to migrate

Step 1: Create a New Vite Project

First, let's create a new Vite project:

npm create vite@latest my-vite-app -- --template react
cd my-vite-app
Enter fullscreen mode Exit fullscreen mode

This command creates a new Vite project with React template. We'll use this as a base for our migration.

Step 2: Move Your Source Code

Now, let's move your existing source code from the CRA project to the new Vite project:

  1. Copy the src directory from your CRA project to the new Vite project, replacing the existing src directory.
  2. Copy any additional directories you may have (e.g., public, assets) to the Vite project root.

Step 3: Update Package.json

We need to update the package.json file to include all the dependencies from your CRA project:

  1. Copy the dependencies and devDependencies from your CRA project's package.json to the new Vite project's package.json.
  2. Remove CRA-specific dependencies like react-scripts.
  3. Add Vite-specific scripts:
"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"
}
Enter fullscreen mode Exit fullscreen mode
  1. Install the dependencies:
npm install
Enter fullscreen mode Exit fullscreen mode

Step 4: Configure Vite

Create a vite.config.js file in the root of your project:

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

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

This configuration sets up the React plugin, defines an alias for the src directory, and sets the development server port to 3000 (matching CRA's default).

Step 5: Update Import Statements

Vite uses ES modules, so you may need to update some of your import statements:

  1. Replace import React from 'react' with import * as React from 'react' in files where you're not using JSX.
  2. Update any imports that use CRA-specific aliases (like src/) to use your new alias (@/) or relative paths.

Step 6: Handle Environment Variables

Vite handles environment variables differently than CRA:

  1. Rename .env files to use the Vite prefix: .env, .env.local, .env.development, .env.production.
  2. Update environment variable usage in your code:
    • Change process.env.REACT_APP_* to import.meta.env.VITE_*
    • In your .env files, rename variables from REACT_APP_* to VITE_*

Step 7: Update Test Configuration

If you're using Jest with CRA, you'll need to switch to Vitest, which is better integrated with Vite:

  1. Install Vitest and related packages:
npm install -D vitest jsdom @testing-library/react @testing-library/jest-dom
Enter fullscreen mode Exit fullscreen mode
  1. Create a vitest.config.js file in your project root:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()],
  test: {
    globals: true,
    environment: 'jsdom',
    setupFiles: './src/setupTests.js',
  },
})
Enter fullscreen mode Exit fullscreen mode
  1. Update your test files to use Vitest syntax (most Jest tests should work with minimal changes).

Step 8: Configure the Proxy Server

If your CRA project used a proxy configuration, you'll need to set it up in Vite:

  1. Install http-proxy:
npm install -D http-proxy
Enter fullscreen mode Exit fullscreen mode
  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)
          })
        },
      },
    },
  },
})
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
  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
})
Enter fullscreen mode Exit fullscreen mode

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!

Top comments (0)