How to Migrate smoothly from CRA to Vite for React & Why Vite is Fast?
Tags: vite, cra, react, webdev
Published: 2024-02-16 07:50:05

## What is Vite JS?


Vite JS, crafted by Evan You, is a non-bundling development environment tailored for Vue.js. Its main aim is to improve the frontend development process by speeding up app development. 

During development, Vite employs native ES Module imports to deliver your code, enabling the creation of Vue.js single-file components without the need for bundling. Originally designed with Vue 3 in mind, Vite also extends its compatibility to other frameworks, such as React.

While initially geared towards Vue 3, Vite JS is versatile and can be applied to other frameworks like TezJS and React.

Positioned as a cutting-edge front-end development tool, Vite JS streamlines the workflow, offering a more efficient and faster approach to building modern web applications. Widely used for setting up development environments across frameworks like React and Vue, and Vanilla JavaScript apps, Vite JS simplifies the process with just three commands, incorporating a development server and hot reloading.

[Vite](https://vitejs.dev/) is a vital link between Twig/Craft CMS and the next-gen front-end build tool Vite.js. Noteworthy features include Hot Module Replacement (HMR) for JavaScript, CSS, and Twig (even in the presence of errors) during development and optimized production builds. 

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.

------------------------------------------------------------------

Now create a beautiful admin interface with ready-to-use admin templates. Experience perfect use of react and vite with [**React Admin Templates**](https://codedthemes.com/item/category/templates/react-admin-templates/).


[![react dashboard](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/llylhlcwen60dzhtvy25.png)](https://codedthemes.com/item/category/templates/react-admin-templates/)

------------------------------------------------------------------

## Steps about how to migrate CRA to Vite

### 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.

```
- 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.

```

```
- 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"
},

```
Tweaking tsconfig.json: [create-vite-app/template-react-ts/tsconfig.json at master · vitejs/create-vite-app (github.com)](https://github.com/vitejs/create-vite-app/blob/master/template-react-ts/tsconfig.json)

### 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)](https://vitejs.dev/guide/assets.html#new-url-url-import-meta-url)

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.

## Why it is Fast?

ViteJS’s remarkable speed is rooted in integrating two key trends that have shaped the web development landscape. Here’s why ViteJS is considered a fast framework:

### 1. Modern JavaScript Adoption:

ViteJS leverages the widely supported modern JavaScript, a language that has become a standard in web development.
The global support for Native ES modules, a key component, exceeds 92%, and this number continues to grow as outdated browsers, like IE11, phase out.

###2. Native Language Data Compilers:

ViteJS leverages the widely supported modern JavaScript, a language that has become a standard in web development.
The global support for Native ES modules, a key component, exceeds 92%, and this number continues to grow as outdated browsers, like IE11, phase out.

### 3. Efficient Hot Module Reloading (HMR):

Traditional workflows involve updating the entire bundle upon file modifications, leading to a time-consuming process to visualize changes.
ViteJS revolutionizes this by using native module imports, ensuring that Hot Module Reload is swift and instantaneous.
This optimization streamlines the development process, making it more responsive and agile.