Author:  How to Migrate smoothly from CRA to Vite for React?

Table of Contents

In the ever-evolving landscape of React development, it’s essential to keep up with the latest recommendations from the React team. One significant shift in their guidance is the move away from Create React App (CRA) as the default bundler for creating new React applications, transitioning from CRA to Vite. The rationale behind this change is rooted in the recognition that while CRA served as a helpful jump-start for many projects, it lacked the flexibility required to configure and manage large, complex applications effectively.

Today, the React team and the community at large are advocating for the use of production-grade React frameworks, such as Next.js, Remix, Gatsby, or Expo for native applications. These frameworks offer a more robust and versatile approach to building and scaling React projects, making them the preferred choice for modern development.

In addition to these frameworks, the React team also suggests considering Vite and Parcel for custom build processes. This shift is partly motivated by the fact that the Create React App package has not received updates for approximately a year. This lack of updates may lead to compatibility issues, especially when working with packages that have moved on to more recent versions.

To ensure your projects stay up-to-date and maintain compatibility with the latest packages, you might need to consider migrating away from CRA and adopting the recommended alternatives, such as Vite or Parcel. This transition can help future-proof your applications and provide greater flexibility in managing their development and deployment.

Are you ready to embark on a journey to enhance your production based React application by migrating from Create React App (CRA) to Vite? This article is your comprehensive guide, not just on the “how,” but also the “why” behind each step of the migration process. You’ll gain a deep understanding of the reasons behind every decision, empowering you to make informed choices as you navigate this transition.

Checkout What is Vitejs, and Why is it Fast?

Step 1: Elevate Your Environment with Vite and Essential Plugins

To kickstart your migration journey, the first step is to bring in the essential tools and plugins that will power your React application in its new home, Vite. These are the commands to get you started:

npm install vite @vitejs/plugin-react vite-tsconfig-paths

In addition to Vite itself, there are two key plugins in above command, each serving a distinct purpose in enhancing your development environment:

1. @vitejs/plugin-react: This plugin is your gateway to a smoother development experience. It introduces fast refresh in development, harnesses the power of automatic JSX runtime, and opens the door to custom Babel plugins and presets. Brace yourself for an enriched React journey!

2. vite-tsconfig-paths: This is to resolving imports seamlessly when dealing with TypeScript’s path mapping. Say goodbye to those cumbersome relative import paths like ./../components/ComponentName. With this plugin, you can embrace cleaner and more efficient import statements such as components/ComponentName.

If you are using JS and jsconfig.json, you can use vite-jsconfig-paths instead vite-tsconfig-paths

Step 2: Crafting Your Vite Configuration

In Vite, create a vite.config.ts file in your project’s root directory to tailor its behavior. Customize it for IntelliSense, environment-specific settings, and more.


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

export default defineConfig({
  // depending on your application, base can also be "/"
  base: process.env.VITE_APP_BASE_NAME,
  plugins: [react(), viteTsconfigPaths()],
  define: {
    global: 'window'
  },
  resolve: {
    alias: [
     
    ]
  },
  server: {
    // this ensures that the browser opens upon server start
    open: true,
    // this sets a default port to 3000
    port: 3000
  }
});

Step 3: Add Vite type support

Vite Types File To enhance type checks and Intellisense, you’ll need a type declarations file. By default, Vite’s types are designed for NodeJS environments. For client-side code, you can access type definitions in vite/client.d.ts. In your project’s root directory, create a vite/client.d.ts file with the following content:

/// <reference types="vite/client" />

Step 4: Relocate and update the index.html

Vite operates with a designated root directory from which your files are served. Because index.html serves as Vite’s server entry point, it must reside in this root directory. To make the necessary adjustment, move the index.html file from the public directory to the root of your project. Make sure it’s at root not inside src directory. Once done there might following two changes needed.

  1. Remove PUBLIC_URL: Vite automagically resolves URLs within the index.html file, eliminating the need for %PUBLIC_URL% placeholders. So, remove any reference of %PUBLIC_URL% from file.
  2. Include Module Script in the Body Tag: Vite views index.html as part of the module graph and resolves <script type="module" src="..."> tags that reference your JavaScript source code. To seamlessly integrate this, simply add the script at the bottom of the body tag in your index.html file, like so:
<!doctype html>
<html lang="en">
  <head>
    ...
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    ...
    <script type="module" src="/src/index.tsx"></script>
  </body>
</html>

Step 5: Transition from CRA to Vite

Removing CRA, Updating Package.json, and Tweaking tsconfig.json

  • Removing CRA: The Command:
npm uninstall react-scripts
  • Using Vite in Your Scripts: Replacing react-scripts
"scripts": {
    "start": "vite",
    "build": "tsc && vite build",
    "preview": "vite preview"
},

Step6: Handling Environment Variables with Vite

  • Update process.env.REACT_APP_VARIABLE(Note: If Your App Doesn’t Use Env Variables, You Can Skip This Step)

Before:

process.env.REACT_APP_VARIABLE

After:

import.meta.env.REACT_APP_VARIABLE
  • Replace REACT_ with VITE_

Before:

REACT_APP_API_URL

After:

VITE_APP_API_BASE

    Step 7: Time to See It Live

    npm run start 

    Troubleshooting

    • After migration, it may possible that your images may not render. If you have dynamic image rendering, it will also not render. To resolve that:
      • Static images: You can set whole path relative to component of image
      • Dynamic images: You get benefit of dynamic asset loading of VITE and render image dynamically. Image can be render as URL. Read more here: Static Asset Handling | Vite (vitejs.dev)
    • Sometimes, your image path works in development but break once you make a production build. You can check your production build in local machine by running following commands and see if that will work when you deploy it.
    npm run build
    npm run preview
      • JS extension issue: If you have used JS extension for your react based project, it will not work. You need to convert that to JSX extension for React based components.

      Conclusion

      Woo-hoo. That’s it. Vite is rising demand of react and other front end-based developer community. Your project should also get benefit of it. I hope above article helps you to migrate your react project smoothly.

      Check more articles –

      Share this:
      Share

      codedthemes

      Comments

      Leave a Reply

      Your email address will not be published. Required fields are marked *

      Popular Products
      Popular Posts