Convert CRA to Vite: Step-by-Step Tutorial

Create React App (CRA) and Vite are two popular tools for React application development. Both tools provide you with a wide range of features to work with your React application.

While CRA has been on the market for several years as a React application build tool, Vite is relatively new. But despite being new, it has already managed to grab the attention of developers with its next-level features.

If you have worked with React applications, you will know how popular CRA is in the React development world.

However, as the working mechanism and dependencies of CRA are a bit old, its popularity is decreasing day by day. Vite on the other hand is offering all the latest features. To taste these latest features a large number of developers are migrating from CRA to Vite.

If you are reading this blog post, you also want to try Vite instead of Create React App (CRA).

In this blog post, you will learn how to convert or migrate your existing CRA project to Vite. Whether your application is in vanilla JavaScript or TypeScript, you’ll learn the process of converting both.

Also, if you want to do a fresh new project with Vite, check this blog post: Create React App with Vite: Step-by-Step Guide

Why Convert CRA to Vite?

The short answer is that Vite is just better than CRA. And why do developers love Vite so much? Because Vite is several times faster than CRA. I mean, it is seriously fast.

See Vite’s core philosophy is to provide the best experience for front-end developers. It is a frontend tooling software that provides more efficiency and productivity to the developer.

Before converting from CRA to Vite let’s take a look at some of the benefits of Vite.

Faster Dev Server Starting

In Vite, you can start a local dev server at least 5 to 8 times faster. Depending on the size of the React application, the CRA takes several seconds to start the dev server. There Vite prepares a dev server in just milliseconds.

This speed is not magic. Rather, Vite achieves this high speed with the browser’s native ESModule support.

Create React App (CRA) bundles your entire application before starting the localhost dev server and then starting the server. As a result, extra time is required during the project bundle process.

Vite can import the assets or files of the application directly into the browser with the help of the ESModule feature. So there is no need to bundle the entire application before starting the local server. That’s why Vite can start a Faster Dev Server from CRA.

Instant Hot Module Replacement (HMR)

In the case of HMR, CRA initially bundles the entire project and then updates it in the browser. Due to this mechanism, hot reloading is a bit slow in CRA.

Sometimes, if the project size is large, it takes up to a second to hot reload. Which gives the developer a bit of a laggy feel.

But the Vite’s hot-railing feature is significantly faster and smoother. It updates almost instantly when you change something in the codebase.

Vite smartly pre-bundles your project. and eliminates the hassle of re-bundling during hot reloading. As a result, you see more reliable and immediate changes in the browser.

Smaller Build Size

Create React App (CRA) uses many unnecessary dependencies. Due to this, React application with CRA results in a large build size

Vite on the other hand prefers a lightweight approach and avoids adding too many unnecessary dependencies.

Also, Vite does better code splitting than CRA. As a result, you get smaller and more efficient bundle sizes.

More Customizable

Vite offers more customizability than Create React App (CRA). You can configure your project according to your needs.

Vite also has the support of using third-party plugins.

CRA on the other hand runs on a ready-to-go and less configurable approach.

Overall Vite is better and smoother than CRA in almost every aspect. Developers loved to experience Vite. And so you should also try it.

To learn more in-depth features and speed comparison of CRA and Vite: Vite vs CRA: A Performance and Feature Comparison

Convert CRA to Vite: Vanilla JavaScript

So let’s see the tutorial to convert CRA to Vite step by step:

Step 1: Uninstall React-Scripts

react-scripts controls the core functionality of CRA. That is, starting the dev server, building the application, and testing the application are all done with the help of react-scripts.

In the migration process from CRA to Vite, we first need to uninstall react-scripts.

To uninstall it, first open a terminal in your React app’s project folder. After that execute the following command:

npm uninstall react-scripts

This command will remove react-scripts from your React app dependencies. And this will disable CRA activity in your React project.

Step 2: Install the Vite Plugin into the React Project

Now we need to install the necessary Vite dependencies. For now, we will install Vite and React plugins in our project.

Once react-scripts is uninstalled, install Vite with the following command:

npm install vite @vitejs/plugin-react --save-dev

The above command will install Vite and its devdependencies into your React project.

Step 3: Edit Package.json File

After Vite and all dependencies are installed we need to mention Vite in the package.json file.

That is, we have to specify that our React application will be run on Vite. To do this, open the package.json file of the React application created by CRA.

Then remove the scripts section from there. And add the new scripts section code given below.

"scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview"
}

You can use Vite’s run and build commands by adding this code to the package.json file.

Step 4: Change File Extension

JavaScript assets files within Create React App (CRA) have the “.js” file extension. But Vite uses the “.jsx” file extension.

So we need to change the extensions of “index.js” and “App.js” in the “src” folder.

Rename the two files “index.js” and “App.js” to “index.jsx” and “App.jsx“.

Step 5: Move “index.html” into the Root Directory

index.html is the entry point of the react app from the browser. That is the homepage of the React application.

According to the Create React App (CRA), the project structure index.html will be inside the public folder. But in Vite’s project structure, index.html should be in the root directory of the project.

So to convert the React app from CRA to Vite we need to move the index.html file from the public folder to the root directory.

This can be done in two ways. Cut and paste the file from the public folder to the root directory. Or it can be done through a command in the terminal. As you like.

To do this through the terminal, open the terminal in the project folder. Then run the following command to paste the index.html file into the root directory:

mv public/index.html .

By executing this command into the terminal, the index.html file will be moved to the root directory.

Step 6: Need Some Changes in “index.html”

After moving the index.html file to the root directory, open the file. Now we need to change some code in the file.

First of all, we need to remove all %PUBLIC_URL% from index.html.

PUBLIC_URL is an environment variable of Create React App (CRA). This is a configuration of Webpack. It helps to navigate the project’s assets.

Since CRA bundles React applications with webpack, PUBLIC_URL is required in CRA-based React projects.

But Vite handles project assets differently. It navigates assets through the browser’s native HTTP requests. So %PUBLIC_URL% should be removed from the Vite-based React project.

Now we need to open the index.html file. And remove “%PUBLIC_URL%” from all places where it is found.

After removing all %PUBLIC_URL% add one more line of code. After <div id="root"></div> add the following code.

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

This code will help to resolve the module graph in the Vite build system.

Step 7: Create Vite Configuration File

To run our React application through Vite, we need a Vite configuration file. All the features of Vite can be customized through the Vite configuration file.

So create a vite.config.js file in the root directory of the React project. Then paste the following codes:

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

export default defineConfig ({
    plugins: [react()]
})

Our process of converting CRA to Vite is done. Now it’s time to run the app.

Step 8: Build or Run The Application

Now execute the following command in the terminal to start Vite’s localhost dev server.

npm run dev

This command will start your local server in just milliseconds. Now just open the URL in the browser and enjoy.

To build the application using Vite:

npm run build

After executing this code, Vite will create a folder named dist inside our React project folder. The dist folder will contain all the production code and assets of the built application.

Convert CRA to Vite: TypeScript Template

Above we have seen the process of converting from CRA to Vite. But that was a React application with a vanilla JavaScript template.

But if your React application is built using TypeScript then how to convert? Now we try to learn those steps.

Although the conversion process is almost the same for vanilla JavaScript and TypeScript. However, there are some changes in the TypeScript template. That’s why I am showing the steps of Typescript separately.

The steps which are similar to vanilla javascript and discussed above will not go into detail here. However, the essential steps will be discussed in detail.

Step 1: Uninstall React-Scripts

Like the vanilla JavaScript template, TypeScript must also uninstall react-scripts first. To uninstall, open a terminal in the React TypeScript project folder. Then execute the below command.

npm uninstall react-scripts

Step 2: Install the Vite Plugin into the React Project

After that use the following command to install Vite as usual.

npm install vite @vitejs/plugin-react --save-dev

This will install Vite in your React TypeScript application.

But sometimes NPM may show an error message during the installation process. Below is a snippet of a possible error:

npm ERR! code ERESOLVE
npm ERR! ERESOLVE could not resolve
npm ERR!
npm ERR! While resolving: vite@5.0.2
npm ERR! Found: @types/node@16.18.65
npm ERR! node_modules/@types/node
npm ERR!   @types/node@"^16.18.65" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peerOptional @types/node@"^18.0.0 || >=20.0.0" from vite@5.0.2
npm ERR! node_modules/vite
npm ERR!   vite@"*" from the root project
npm ERR!   peer vite@"^4.2.0 || ^5.0.0" from @vitejs/plugin-react@4.2.0
npm ERR!   node_modules/@vitejs/plugin-react
npm ERR!     @vitejs/plugin-react@"*" from the root project
npm ERR!
npm ERR! Conflicting peer dependency: @types/node@20.10.0
npm ERR! node_modules/@types/node
npm ERR!   peerOptional @types/node@"^18.0.0 || >=20.0.0" from vite@5.0.2
npm ERR!   node_modules/vite
npm ERR!     vite@"*" from the root project
npm ERR!     peer vite@"^4.2.0 || ^5.0.0" from @vitejs/plugin-react@4.2.0
npm ERR!     node_modules/@vitejs/plugin-react
npm ERR!       @vitejs/plugin-react@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR!
npm ERR! For a full report see:
npm ERR! C:\Users\Bond\AppData\Local\npm-cache\_logs\2023-11-28T05_42_33_820Z-eresolve-report.txt

npm ERR! A complete log of this run can be found in: C:\Users\Bond\AppData\Local\npm-cache\_logs\2023-11-28T05_42_33_820Z-debug-0.log
PS E:\Work\KingsCoder\React Arrow Function\cra> npm install vite @vitejs/plugin-react --save-dev
npm ERR! code ERESOLVE
npm ERR! ERESOLVE could not resolve
npm ERR!
npm ERR! this command with --force or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR!
npm ERR! For a full report see:
npm ERR! A complete log of this run can be found in: C:\Users\Bond\AppData\Local\npm-cache\_logs\2023-11-28T05_42_53_736Z-debug-0.log

NPM shows an error message during the Vite plugin installation.

If you face such an error, then execute the below command:

npm install vite @vitejs/plugin-react --save-dev --legacy-peer-deps

Hopefully, this code will fix the Vite plugin installation error.

Step 3: Edit Package.json File

This step is almost the same as the vanilla JavaScript template. There are only slight code changes.

Just open the TypeScript project’s package.json file and paste the following code.

"scripts": {
    "dev": "vite",
    "build": "tsc && vite build",
    "preview": "vite preview"
}

Step 4: Move “index.html” into the Root Directory

This step is the same as the step 5 discussed above. That is, move the index.html file from the public folder to the root directory.

Step 5: Need Some Changes in “index.html”

Open the index.html file. Now remove all %PUBLIC_URL% from the codebase. A detailed explanation of why to remove %PUBLIC_URL% is given in step 6 above.

Now find <div id="root"></div>. After this, the following code should be added in the next line.

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

This line of code will allow the browser to import your app’s index.tsx TypeScript file.

Step 6: Create Vite Configuration File

Create a vite.config.ts file inside the TypeScript React project folder. This is Vite’s configuration file. It operates all the Vite features.

After creating the vite.config.ts file, then paste the following code there:

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

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
})

If you want Vite to open on a specific port then you can add the below code:

export default defineConfig({
  plugins: [react()],
  server: {
    port: 3000
  }
})

If you want to open the localhost URL automatically:

export default defineConfig({
  plugins: [react()],
  server: {
    port: 3000,
    open: true
  }
})

Saving the vite.config.ts file completes the conversion of our TypeScript React project from CRA to Vite.

Step 7: Build or Run The Application

Finally, the conversion process is finished. Now to start Vite Dev Server:

npm run dev

To build the project for production:

npm run build

The above command will bundle your project for production.

When building a project with TypeScript React, you may encounter some problems with SVG files. This is because SVG is not a javascript file. So it cannot be imported directly.

In this case, you can solve the problem by declaring an SVG file as a string data type. An example is given below:

const logo = require("./logo.svg") as string;

You can store your SVG files as strings in variables.

Use Vitest for Testing: Optional

Create React App uses the Jest framework for testing by default. In most cases, Jest works just fine.

However, since you have uninstalled react-scripts during Vite installation, the default npm test command will not work.

In this case, you can use Vitest to replace Jest. Vitest is much faster and lightweight compared to Jest.

To install Vitest as a dev dependency:

npm install vitest --save-dev

After that update your package.json file:

"scripts": {
    "dev": "vite",
    "build": "tsc && vite build",
    "preview": "vite preview",
    "test": "vitest"
}

Now you can test using Vitest. In the future, I will come up with a full detailed blog post about the migration from Jest to Vitest.

Fix CJS Build of Vite’s Node API is Deprecated

When you start Vite’s dev server or build a project, it shows a warning in the terminal. Which is the CJS Build of Vite’s Node API is Deprecated.

This is because Vite uses the ESM mechanism for building. And Vite will completely remove CJS from version 6.

This is quite easy to fix. Just add the following code to your project’s package.json file.

"type": "module"

Adding this will fix that warning message showing from Vite.

The Final Point

We learned the benefits of using Vite instead of CRA in this blog post. Also learned the steps on how we can migrate from CRA to Vite.

Vite is truly an amazing tool. Hope you enjoy working with it. And for more details about Vite, you can check their official documentation.

But before going let me tell you an important tip. Although this post talks about converting from CRA to Vite. But I would suggest rebuilding your React application using Vite if possible.

Because CRA installs many unnecessary dependencies. It is very troublesome to remove all of them one by one. But if rebuilding your project seems like a hassle then follow the migration process.

Anyway, so far today. If you have something to share, please comment below. Happy Coding!

Leave a Comment

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

Scroll to Top