Upgrade Your React App: Moving from Create React App to Vite

Welcome to the very first edition of my newsletter! I'm excited to announce that this will be a monthly publication where I'll share a mix of original articles that I've written and curated content that I find particularly interesting and insightful. I hope you'll find the topics engaging and look forward to sharing this journey with you. Stay tuned for more updates and discoveries each month!

In the ever-evolving landscape of web development, tools and technologies continuously emerge to enhance productivity and performance. One such tool making waves in the community is Vite, a modern build tool that promises faster development times and a more streamlined build process. If you've been using Create React App (CRA) for your React projects, you might be familiar with its ease of setup but also its longer build times and somewhat rigid configurations. Migrating your React application from CRA to Vite can significantly improve your development workflow, offering faster build times, improved performance, and a more flexible configuration system.

This guide aims to provide a comprehensive, step-by-step approach to help you seamlessly transition your React project from Create React App to Vite. By following these detailed instructions, you'll be able to leverage the modern features of Vite while maintaining the structure and functionality of your existing application. Whether you're seeking faster development, optimized builds, or simply a more enjoyable coding experience, this migration guide is designed to meet your needs and set you on the path to modern development with Vite.

What is Vite?

Vite is a modern build tool, designed to provide a faster and leaner development experience for modern web projects. Vite leverages native ES modules in the browser and takes advantage of new JavaScript features to deliver a highly efficient and speedy development environment.

Why Migrate to Vite?

Migrating to Vite can offer several benefits over Create React App (CRA), including faster development, modern JavaScript usage, optimized builds, and greater flexibility. Vite provides a faster development server with near-instant hot module replacement (HMR), making development much quicker and more efficient. It uses native ES modules, which means less overhead and faster compilation times. Additionally, Vite’s build process is optimized for speed and performance, resulting in smaller, faster-loading production builds. Its configuration is also simpler and more flexible than CRA, allowing for easier customization. Migrating your React app to Vite can significantly improve your development workflow and application performance.

Step-by-Step Migration Guide

Step 1: Install Vite and Required Plugins

To start the migration, install Vite and the necessary React plugins as development dependencies. This involves running the command npm install vite @vitejs/plugin-react --save-dev. This step is essential because Vite is the new build tool and development server you’ll be using instead of react-scripts. The @vitejs/plugin-react plugin is necessary for Vite to understand and correctly process your React code, including JSX syntax.

Step 2: Uninstall Create React App Dependencies

Next, you need to remove the react-scripts package that comes with Create React App by running npm uninstall react-scripts. This is crucial because react-scripts is a set of scripts and configurations used by Create React App to manage the build process and development server. Since you’re switching to Vite, react-scripts is no longer needed and can be safely removed to avoid conflicts.

Step 3: Adjust package.json

Update your package.json to use Vite's scripts by replacing the existing scripts with the following:

"scripts": {
  "start": "vite",
  "build": "vite build",
  "serve": "vite preview"
}

These script changes are necessary to instruct npm (or yarn) on how to start the development server, build the project, and serve the production build using Vite’s commands. The start script runs the Vite development server, build compiles your application for production, and serve allows you to preview the production build locally.

Step 4: Rename JSX and TSX Files

Vite requires explicit file extensions for JSX and TSX files. You need to rename all .js files that use JSX to .jsx and .ts files to .tsx. To automate this process, create a new batch file (e.g., rename-jsx.bat). Paste the following commands into the batch file:

@ECHO OFF
PUSHD .
FOR /R %%d IN (.) DO (
cd "%%d"
IF EXIST *.js (
REN *.js *.jsx
)
IF EXIST *.ts (
REN *.ts *.tsx
)
)
POPD

Then, double-click the batch file to rename your files. This script automates the process of renaming files across your project directory, saving you time and ensuring consistency. Running the script ensures that all your JSX and TSX files are correctly named, which is crucial for Vite to properly process these files.

Step 5: Create vite.config.js

In the root directory of your project, create a new file named vite.config.js. This file will contain your Vite-specific configuration, which is necessary to customize how Vite builds and serves your project.

Step 6: Configure Vite

Add the following configuration to vite.config.js:

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

export default defineConfig(() => {
  return {
    build: {
      outDir: 'build',
    },
    plugins: [react()],
  };
});

This configuration tells Vite to use the React plugin and specifies that the production build should be output to the build directory, matching the behavior of Create React App.

Step 7: Update index.html

Move public/index.html to the root directory of your project by running mv public/index.html .. Vite expects the index.html file to be in the root directory, as it uses this file as the entry point for your application. Edit index.html to remove any %PUBLIC_URL% placeholders, for example:

<link rel="icon" href="/favicon.ico" />

Vite doesn’t support the %PUBLIC_URL% syntax used by Create React App, so you need to replace these with relative paths. Add the following script tag after the <div id="root"></div>:

<script type="module" src="/src/index.jsx"></script>

This script tag tells Vite where to find the entry point of your React application, allowing it to correctly load and execute your code.

Step 7.1: Move index.html

Move public/index.html to the root directory of your project.

mv public/index.html .

Step 7.2: Remove %PUBLIC_URL% Occurrences

Edit index.html to remove any %PUBLIC_URL% placeholders.

<link rel="icon" href="/favicon.ico" />

Step 7.3: Add Script Tag

Add the following script tag after the <div id="root"></div>:

<script type="module" src="/src/index.jsx"></script>

Step 8: Update Environment Variables

Rename all environment variables from REACT_APP_ to VITE_ in your .env files. Vite uses a different prefix for environment variables (VITE_) to avoid conflicts with other tools and to clearly identify which variables are meant for Vite. Additionally, update the imports in your code from process.env.REACT_APP_... to import.meta.env.VITE_.... Vite accesses environment variables through import.meta.env, which is a different approach compared to Create React App’s use of process.env. Updating these references ensures that your environment variables work correctly in Vite.

Step 8.1: Rename Variables

Rename all environment variables from REACT_APP_ to VITE_ in your .env files.

Step 8.2: Update Imports

Update the imports in your code from process.env.REACT_APP_... to import.meta.env.VITE_....

Step 9: Full vite.config.js Configuration

For a more comprehensive configuration, especially if you use aliases and SVGs, update vite.config.js as follows:

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

export default defineConfig(() => {
  return {
    resolve: {
      alias: [
        { find: '@', replacement: path.resolve(__dirname, 'src') },
        { find: 'styles', replacement: path.resolve(__dirname, 'src/styles') },
        {
          find: 'modules',
          replacement: path.resolve(__dirname, 'src/modules')
        },
        { find: 'assets', replacement: path.resolve(__dirname, 'src/assets') },
        {
          find: '~bootstrap',
          replacement: path.resolve(__dirname, 'node_modules/bootstrap')
        }
      ]
    },

    server: {
      port: 3000,
      host: true
    },
    build: {
      outDir: 'build'
    },
    plugins: [react(), svgr({ svgrOptions: { icon: true } })]
  }
})

Including this configuration helps to define custom aliases for module imports, making your import paths cleaner and more maintainable. The server section allows you to specify the port and host for the development server, ensuring that your development server runs on the specified port and can be accessed on your local network, which is useful for testing on different devices. The svgr plugin enables importing and using SVG files as React components, which is useful if your project uses a lot of SVGs.

Step 9.1: Alias Imports

If you want to use alias imports in your Vite project, include:

import path from 'path';

Step 9.2: Define Aliases

Add alias definitions:

alias: [
  { find: '@', replacement: path.resolve(__dirname, 'src') },
  { find: 'styles', replacement: path.resolve(__dirname, 'src/styles') },
  { find: 'modules', replacement: path.resolve(__dirname, 'src/modules') },
  { find: 'assets', replacement: path.resolve(__dirname, 'src/assets') },
  { find: '~bootstrap', replacement: path.resolve(__dirname, 'node_modules/bootstrap') }
]

Step 9.3: Server Configuration

Configure the server to open the browser and specify the port:

server: {
  port: 3000,
  host: true
}

Step 9.4: SVG Support

Install vite-plugin-svgr and update the configuration to use it:

npm i vite-plugin-svgr

In vite.config.js:

import svgr from 'vite-plugin-svgr';
// ...
plugins: [react(), svgr({ svgrOptions: { icon: true } })]

Step 10: Happy Hacking!

Run your application to ensure everything works as expected by executing the command npm start. Congratulations! You have successfully migrated your React app from Create React App to Vite. Running your application confirms that the migration was successful and everything is working correctly.

Migrating your React application from Create React App to Vite can seem daunting, but the benefits of faster builds, improved performance, and a modern development experience are well worth the effort. By following this detailed guide, you've taken a significant step towards optimizing your workflow and embracing the latest in web development technology.

Vite’s streamlined configuration and efficient development server will enhance your productivity, allowing you to focus more on writing great code and less on waiting for builds. Remember, the transition to new tools is part of the journey in the fast-paced world of development. Embrace these changes, and you'll continuously improve your skills and your projects.

Thank you for following along with this migration guide. I hope you find Vite as beneficial to your development process as many others have. Happy coding!

If you found this usefull, you can buy me a coffee!

Finally, I'm thrilled to announce my brand-new Udemy course: "React in 10 Steps: Build a Complete Todo App from Scratch!" Ready to transform your web development skills? This course is your ultimate guide to mastering React while building a powerful Todo app.

What You'll Learn:

  • React Fundamentals

  • CRUD Operations

  • Advanced State Management

  • Performance Optimization

  • Middleware Handling

  • Routing with React Router

  • Asynchronous HTTP Requests with Axios

  • Real-World Application Techniques

  • Seamless Deployment

This course is designed for both beginners and seasoned developers looking to sharpen their skills. You'll get hands-on experience, actionable insights, and the confidence to build real-world React applications.