Migrating from Create React App (CRA) to Vite (2023)

I recently migrated a production app at my company from create-react-app (CRA) to Vite and the results so far have been great.

In this article, I'll cover all the steps I took during the migration, hoping to help others who are going through the same process.

Why change?

I would like to start by saying that I really like CRA, it has helped me to set up and manage many projects (personal and professional) quickly. However, here are some of the reasons why we decided to make the switch:

  • No dedicated supervisor.
  • Release slowly. This will only lead to more issues later on as more features are added to React and Webpack.
  • Growing number of github-dependent bot warning vulnerabilities that our security team needs to patch, whether it's a build tool or not.
  • Speed. This wasn't really an issue for me as I rarely restart my development server and my CI pipeline handles the production build for me. That said, the app I'm migrating is quite small, so this might be a bigger issue for those with larger, more complex apps. I certainly wouldn't migrate for that reason alone, but I have to admit that the speed improvements are pretty impressive.
  • Vite has matured a lot and the community has grown significantly compared to when I created this CRA-based app 2 years ago. If I were to re-evaluate both for a new project, I would choose Vite this time around.

Given all this, I thought it was time to make the switch.

The only real "con" to using Vite is that you don't write your code yourself, you just transpile it into javascript. Personally, I think that's OK, as many IDEs have great Typescript support these days.

migration steps

These are all the steps I took to migrate from CRA to Vite. It's worth mentioning that I'm migrating a Typescript project, although most of the steps should be similar to Javascript projects.

Let's start! 🇧🇷

1. Install dependencies

We need to install these 4 dependencies:

npm install --save-dev vite @vitejs/plugin-react vite-tsconfig-paths vite-plugin-svgr

Use:

We needvite-tsconfig routesto tell Vite how to resolve absolute paths from the tsconfig. That way you can import modules like this:

(Video) Converting to Vite from Create React App - lower your boot time to almost nothing!

Import MyButton from 'Components'

Rather than

import MyButton from '../../../components'

We needvite-plugin-svgrto import SVG as React components. For example:

importie { ReactComponent as Logo } como './logo.svg'.

2. Create Vite configuration file

To... createvite.config.tsat the root of your project. This is where you set all of Vite's configuration options.

to import{defineConfig}Von 'fast';to importto reactVon '@vitejs/plugin-react';to importviteTsconfigPathsVon 'vite-tsconfig routes';to importsvgr add-onVon 'vite-plugin-svgr';// https://vitejs.dev/config/To export OriginallydefineConfig({ complementos: [react(), viteTsconfigPaths(), svgrPlugin()],});

3. Moverindex.html

move itindex.htmlfile of/Advertisingfolder in the root of your project. Find out why this is being doneon here.

4. Updateindex.html

URLs are handled slightly differently in Vite, so we need to remove all references to%PUBLIC_URL%🇧🇷 For example:

// In front of<link rel="Symbol"href="%PUBLIC_URL%/favicon.ico"/>// After this<shortcut real="Symbol" href="/favicon.ico"/>

We also need to add an entry point to it.<body>Element:

<Text>You must enable JavaScript to run this application.</Text><division I would like to="Source"></division><!-- Add entry point 👇 --><text type="Module" Those ones="/src/index.tsx"></text>

5. Updatetsconfig.json

The main thing you need to update intsconfig.jsonfile aremeta,launchyThe type🇧🇷 For example:

(Video) Switching from Create React App to Vite

{"Compiler Options": {"meta":"ESNext","lib": ["Dom","dom.iterable","the next"],"the type": ["fast/customer","vite-plugin-svgr/client"],"allowJs":INCORRECT,"saltarLibCheck":INCORRECT,"esModuleInterop":INCORRECT,"allow synthetic default imports":real,"strictly":real,"forceConsistentCasingInFileNames":real,"noFallthroughCasesInSwitch":real,"Module":"ESNext","module resolution":"It","resolverJsonModule":real,"isolated modules":real,"noEmit":real,"jsx":"react-jsx"},"contains": ["source"]}

You can also have a look at Vitestsconfig.jsonoffice houron hereFor reference.

6. Createfast-ca.d.tsoffice hour

Since we are using Typescript, we need to create afast-ca.d.tsfile under theThose onesFolder with the following content:

/// <reference types="guest/customer" />

7. Deletereaction script

It's time to say goodbye to CRA once and for all. 👋 Run this command to uninstall it:Uninstall npm react scripts.

We can also remove them.react-application-env.d.tsFile, File.

8. Update the scripts inpackage.json

how we eliminatereaction script, now we need to update the scripts insidepackage.jsonreferencefastinstead:

"hifens": {"to start":"fast","accumulate":"tsc && compilation vite","to serve":"Visit Preview"},

9. Get started!

once you runstart npm, you should now see your app open in the browser, powered by the awesome Vite.

If your app is small enough, this might be all you need to do. If not, read on for more optional steps.

optional steps

Here are some additional optional steps you can take based on your own project setup.

ESLint and prettier

I wrote a separate guide on how to configure ESLint & Prettieron here.

exams

I also wrote a guide on how to replace Jest with Viteston here.

(Video) From create-react-app to vite

environmental variables

It's very easy to migrate environment variables, just rename themREACT_APP_oneFAST_that back.envfiles. I just did some research and replaced them and it worked perfectly.

Instead of referencing variablesprocesso.env.REACT_APP_, you'll useimport.meta.env.VITE_.

You can go further and specify types for your environment variables by creating aenv.d.tsfile inThose onesArchive. For example:

InterfaceImportMetaEnv {only readingVITE_TOKEN:line;only readingQUICK_CUSTOMER_ID:number;}Interfaceimport target {only readingenvironment: ImportMetaEnv;}

If you need to browse node environments (i.e. development or production) you can do so using theimport.meta.envObject:

e(to import.meta.env.DEV) {// just do something in development mode}e(to import.meta.env.PROD) {// just do something in production mode}

For more information on environment variables, seethese documents.

Change build output folder

In Vite the default production build folder name isDistance, you can change this to the default CRA settingaccumulatePaste if necessary. I found it useful because my CI/CD scripts point to it.accumulate.

// vite.config.tsTo export OriginallydefineConfig({ ... compilation: { outDir:'accumulate', },});

Automatically open app on server startup

One thing I liked about CRA was that it automatically opened the application in the browser when the server was started. Vite also has this option:

// vite.config.tsTo export OriginallydefineConfig({ ... server: { open:real, },});

change the port number

If you need to change the default port number3000, specify like this:

// vite.config.tsTo export OriginallydefineConfig({ ... Server: { Port:4000, },});

Reference points

Here are some benchmarks I recorded before and after the migration:

CRAFast
install npm21 seconds9 seconds
Server start time (cold)11 seconds856 milliseconds
the tests are running17 seconds14 seconds
production setup45 seconds17 seconds
Production facility size.886 KB / gzip: 249 KB656,91 KB / gzip: 195,21 KB
(Video) Tauri & ReactJS Part 5 - Migrating CRA to Vite

You can really see the improvements in server startup time, but other than that there wasn't much of a difference. Keep in mind though that this was a very small app and could be even more important for these larger apps.

Problems solution

Here are some errors you might encounter:

1. During executionstart npmI see the following error:Error: Cannot find module 'node:path'.

Answers:Joyait's problem, you should make sure you've updated youritrelease the14.18.0ov16+.

2. During executionstart npmI see the following error:No matching export on MODULE_NAME to import TYPE_NAME.

Answers:This usually happens when using a library with aemPackage where Vite waitsWITHcurl. this happened to meokta-authorización-jsand the solution was to specifically tell Vite to load the fileemPackage in Vite config file:

// vite.config.tsTo export OriginallydefineConfig({ ... resolvedor: { alias: {'@okta/okta-autorización-js':'@okta/okta-auth-js/dist/okta-auth-js.umd.js', }, },});

3. My screen is blank after runningstart npm.

Answers:Following steps 3 and 4, make sure you have moved and updated theindex.htmlFile, File.

try thisVite Troubleshooting docsfor more.

final thoughts

Overall, I'm very happy with the Vite. The migration was smooth and the developer experience was significantly improved. You can do everything CRA does, but with better implementations. If you found this article helpful or have additional tips, please leave a comment below. 🇧🇷

(Video) Convert React app to Next JS app | CRA to NEXT JS

Do you want to see more?

I mostly write about real tech issues I face in my everyday life as a frontend developer. If that tickles your fancy, feel free to follow me on Twitter:https://twitter.com/cmacdonnacha

See you soon 👋

FAQs

What is the difference between Vite and CRA? ›

Unlike CRA, Vite does not build your entire application before serving, instead, it builds the application on demand. It also leverages the power of native ES modules, esbuild, and Rollup to improve development and build time. Let's take a look in detail at what can make CRA slow.

What is the difference between react create react app and Vite? ›

Vite and CRA are not as different as you might think. At their core, they pretty much do the same thing, which is to serve a local development server and bundle codes for production. The major difference you'll notice is how code is served in development and which modules are supported.

How do I use Vite with create react app? ›

  1. Prerequisites.
  2. Step 1 — Creating a Vite Project.
  3. Step 2 — Starting the Development Server.
  4. Step 3 — Previewing Your App from Mobile Phone.
  5. Step 4 — Removing the Default Boilerplate.
  6. Step 5 — Creating a Basic App.
  7. Step 6 — Building for Production.
  8. Conclusion.
May 5, 2022

What can I use instead of CRA? ›

NextJS is probably the most popular toolchain besides CRA. It comes with its own routing and styling solutions (styling can be tricky when working with SSR). Vercel, the maintainer of NextJS, is also responsible for other packages that can be used in any React project (e.g., swr).

How do I migrate from CRA to Vite? ›

Here are all of the steps I took to migrate from CRA to Vite.
...
Migration steps
  1. Install dependencies. We need to install these 4 dependencies: ...
  2. Create Vite config file. Create a vite. ...
  3. Move index.html. Move the index. ...
  4. Update index.html. ...
  5. Update tsconfig. ...
  6. Create vite-env.d.ts file. ...
  7. Remove react-scripts. ...
  8. Update scripts in package.
Aug 22, 2022

Why Vite is better than Create React app? ›

Vite is a build tool similar to Webpack. It can be used for React, Preact, Svelte, Vue, Vanilla JS, and LitElements. Vite is 100 times faster than Webpack and bundles your code with Rollup, pre-configured to output highly optimised static assets. Your browser does not support the audio element.

Should I use Vite instead of create React app? ›

Vite gives you same fast start, but you don't have this blackboxed config that is too scary to look at. This also means that if you need something additional, your config will grow with your app, and wouldn't try and solve problems before those problems will occur. Vite is also very fast and convenient to use.

Is it OK to use create React app? ›

Why it is better to avoid Create React App (CRA) CRA was created for beginners (according to Facebook) to learn React without understanding the underline configurations of Webpack. However, it is not created for production. Unfortunately, devs have been using it for all their projects.

Should I still use create React app? ›

Even if it's your first time using React, you shouldn't be using Create React App. Create React App is what almost every developer (including myself) learned to use first when learning the JavaScript library React and I think this has led to a couple of significant flaws.

When should I use Vite? ›

Vite represents a quick, easy-to-use environment that doesn't require long builds to get started with a project. Although it's not a perfect solution for every project, it can speed up development quite a bit, especially in large projects where its ability to just hot-swap whole modules can really help.

What are the advantages of Vite? ›

Vite improves the dev server start time by first dividing the modules in an application into two categories: dependencies and source code. Dependencies are mostly plain JavaScript that do not change often during development.

Is Vite better than Webpack? ›

While a bundler-based workflow like Webpack will have to process your entire JavaScript modules before a single browser request, Vite only processes your dependency modules before a single browser request. This is why Vite is able to process your development build faster than Webpack.

Can I use Vite for production? ›

When it is time to deploy your app for production, simply run the vite build command. By default, it uses <root>/index. html as the build entry point, and produces an application bundle that is suitable to be served over a static hosting service.

Why React developers are paid more? ›

More and more software companies insist to hire skilled React developers. Being a renowned and in-demand technology, it demands a certain level of expertise to offer the best development work. To accomplish certain sets of projects, companies are looking to hire ReactJS developers with exceptional skills.

What is the advantage of using create React app? ›

Create React App enables you to include styles by importing the necessary CSS files. While building the application, every CSS file would be concatenated into one bundle. Subsequently, it will be adjoined to the build folder. Create React App supports CSS modules as well.

Do I need Babel with Vite? ›

Plus you don't need Babel if you're using Vite so you can get rid of a tonne of dependencies and security vulnerability messages.

Is Vitejs production ready? ›

Vite provides a build command to create an optimized and production-ready build of our application. During the build, Vite also optimizes our static assets like images, etc.

Should I use create React app or Nextjs? ›

Should I Use Next JS or CRA? Typically if you have an application that will only be used behind a login, CRA is a good choice. However, if you have an application for which SEO is important and fast page loads are critical, then Next JS is the right solution.

Is Vite like Webpack? ›

The core functionality of Vite is similar to webpack + webpack-dev-server with some new improvements and functionalities on developer experience, such as: Regardless of app size, you'll spend less time waiting for your app to start. HMR (Hot module Reloading) is an instant, irrespective of the size of the app.

Who is the best React developer in the world? ›

List of the Top React Native Developers
  • Moove It. Developing Impact. ...
  • 5StarDesigners Ltd. A cutting-edge digital company. ...
  • Callstack. React & React Native community-trusted developers! ...
  • GeekyAnts. Web and Mobile App Development Experts. ...
  • UIG Studio. ...
  • Pagepro. ...
  • Technology Rivers. ...
  • Vincit.

Which is the best CMS for React? ›

Hygraph is one of the best choices for a "React CMS" because it based 100% on GraphQL and, as such, helps makes working with your structured content as simple as possible.

Is create React app a MIT license? ›

Create React App is open source software licensed as MIT. The Create React App logo is licensed under a Creative Commons Attribution 4.0 International license.

What is the disadvantage of create React app? ›

Disadvantages of CRA
  1. Difficult to add custom build configs. One way to add custom configs is to eject the app, but then it overrides the Only one build dependency advantage. ...
  2. Abstracts everything. It's important to understand the things that need to run a React app. ...
  3. CRA is bloated - IMO.
Aug 1, 2020

Is Netflix made using React? ›

Netflix also uses React, notably on their Gibbon platform, which is utilized for low-performance TV devices rather than the DOM used in web browsers. Significant reasons like notably start-up speed, runtime performance, and modularity made them choose React.

Is Netflix build with React? ›

Netflix uses ModeJs with the assistance of React for image synthesis. In this article, we have also incorporated a React Netflix clone project with source code which is also available on Netflix clone react js Github. This article will also help you in checking out the Netflix clone project report.

Is React still relevant 2022? ›

The short answer is YES! As we can see from the benefits listed in this article, it is easy to see why React is still enjoying its popularity in 2022. It was voted the 2nd most popular web framework for developers, only falling behind Node. js (see above) 2022 in the reliable StackOverflow Developer Survey 2022.

Is React still worth learning 2022? ›

According to the Stack Overflow Survey, React was the number one web framework used by software developers worldwide in 2021 but, according to the data provided by Statista, in 2022, this framework was overtaken by Node. js, with 47.12% of web developers using this framework against 42.62% of React users.

Are React developers in demand 2022? ›

According to a Statista study, React JS is the most in-demand web framework in 2022, with 40.41% of software developers globally indicating they use it to develop web applications. This has led to an increase in React JS developers demand and, correspondingly, an increase in their salaries.

Why Vite is faster than Webpack? ›

With Vite and code-splitting, your browser will only fetch JS files in small batches, resulting in much better performance. But Webpack isn't as far behind as one may think. Available since 5.20, Webpack can defer compilation of dynamically imported modules.

Is Vite only for frontend? ›

Many of the developers are in a dilemma to consider Vite as a framework or tool. So, let me clear the fog that Vite is a frontend dev tool, which supports any frontend framework, with supported templates for Vue, TezJS, React, Preact, Lit Element, Svelte, and vanilla JavaScript. However, Vite is not only Vue-specific.

What are alternatives to Vite? ›

Webpack, gulp, Grunt, Parcel, and rollup are the most popular alternatives and competitors to Vite.

Which companies use Vite? ›

Get the full list of websites and companies using Vite.
...
Websites using Vite.
#WebsiteTraffic
1daisyui.com12%
2nytimes.com5%
3svelte.dev4%
4kit.svelte.dev3%
6 more rows

Does Vite use Webpack or rollup? ›

Vite uses Rollup to perform a more aggressive dead-code elimination (tree shaking) than Webpack, which is why it takes longer to create a production build.

Is Vue using Vite? ›

Vite is a build tool created by Evan You, the creator of Vue. It allows for faster development thanks to super fast Hot Module Reload (HMR), fast cold start times, and CSS + JSX + TypeScript support out of the box.

Is Vite using rollup? ›

Vite can be extended using plugins, which are based on Rollup's well-designed plugin interface with a few extra Vite-specific options. This means that Vite users can rely on the mature ecosystem of Rollup plugins, while also being able to extend the dev server and SSR functionality as needed.

What makes Vite different? ›

Vite improves the dev server start time by first dividing the modules in an application into two categories: dependencies and source code. Dependencies are mostly plain JavaScript that do not change often during development.

What is the US version of CRA? ›

The CRA provides the information to the Internal Revenue Service (IRS) in the U.S. and the IRS provides the CRA with information on accounts of Canadian residents held at U.S. financial institutions.

What does Vite do? ›

Vite. js allows developers to set up a development environment for frameworks like Vue, TezJS and React and even for Vanilla JavaScript app with a dev server. Moreover, it allows the development team to hot reload in just three commands. Vite supports Rollup.

What is the advantage of using Vite? ›

A huge advantage of using Vite, as we already established, is blazing fast start-ups with instant hot module replacement. It's much faster than other CLIs, such as Create React App or Vue CLI, which use webpack under the hood. Out-of-the-box support for TypeScript.

Should I learn Vite or Webpack? ›

The difference between the two boils down to speed. Webpack is building the project from source and continuing to do incremental builds as you are developing your project. Vite, on the other hand, is loading your actual code into the browser as needed.

Videos

1. Vite is The New Webpack and Create-React-App killer!
(CoderOne)
2. How to Convert React CRA to React Vite
(Software-force)
3. Vite in 100 Seconds
(Fireship)
4. How to Migrate From Create-React-App 4 to 5
(Relatable Code Tutorials)
5. Vite quick tip - Vite with React and Typescript
(Weibenfalk)
6. STOP Using Create React App
(Theo - t3․gg)
Top Articles
Latest Posts
Article information

Author: Mrs. Angelic Larkin

Last Updated: 03/05/2023

Views: 6036

Rating: 4.7 / 5 (67 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Mrs. Angelic Larkin

Birthday: 1992-06-28

Address: Apt. 413 8275 Mueller Overpass, South Magnolia, IA 99527-6023

Phone: +6824704719725

Job: District Real-Estate Facilitator

Hobby: Letterboxing, Vacation, Poi, Homebrewing, Mountain biking, Slacklining, Cabaret

Introduction: My name is Mrs. Angelic Larkin, I am a cute, charming, funny, determined, inexpensive, joyous, cheerful person who loves writing and wants to share my knowledge and understanding with you.