Femil Patodiya
Written By Femil Patodiya ReactJS Developer

Choosing Vite Over Create-React-App (CRA)

post date
February 19, 2024
Choosing Vite Over Create-React-App
Reading Time: 6 minutes

Create React App (CRA) has historically been the preferred tool for constructing React apps among developers of all skill levels, from beginners to experts.

However, as project size increases, longer development and build times become evident. This gradual feedback loop can significantly impact developer productivity and satisfaction.

To tackle these challenges, a new addition to the front-end tooling ecosystem has emerged: Vite!

Unlike CRA, Vite adopts a different approach by not building your entire application before serving. Instead, it builds the application on demand. Additionally, it harnesses the capabilities of native ES modules, Esbuild, and Rollup to enhance both development and build times.

Introducing Vite

Vite is a tool that makes web development faster and better. It helps developers create modern websites quickly and efficiently.

Developed by Evan You, the creator of Vue.js, Vite is a versatile tool that supports JavaScript and TypeScript applications. It works seamlessly with popular libraries such as React, Svelte, Preact, and even plain JavaScript.

It consists of two major parts:

  • A dev server that provides support for Hot Module Replacement (HMR) for updating modules during the execution of the application. When changes are made to the source code of an application, only the changes are updated, rather than the entire application. This feature helps speed up development time.
  • A build command that bundles your code with Rollup, pre-configured to output highly optimized static assets for production.

How Vite Works: A Closer Look

The problem with the tools mentioned above is that they have to build everything on every save, and if you have a very large application, that could take several minutes every time you save, even with Hot reloading in some frameworks, the update speed gets significantly slower as you add more code and dependencies to the app.

Vite has taken a different approach to this, kind of a reverse approach. Vite starts the server right away, takes the dependencies that don’t change often, and pre-bundles them using esbuild.

Let’s take a look at the illustrations below to get a better understanding of how it works.

Bundle Based Dev Server

The above diagram represents a traditional bundle-based development server, where we have an entry point, the possible routes, and all the modules, which are then bundled together, and then the development server is ready.

Vite, on the other hand, uses route-based code-splitting to figure out what parts of the code need to be loaded and doesn’t have to pre-bundle everything.

Native ESM Based Dev Server

Vite serves the source code using native ES Module support in modern browsers. This lets the browser take the job of bundling in development, which consequently makes your code load instantly, no matter how large the app is.

It also supports Hot Module Replacement for an extremely fast feedback loop during development.

When building for production, Vite uses Rollup under the hood, so you don’t have to worry about configuring it.

Benefits of building a dev server around native ESM

Benefits of Building a Dev Server around native ESM

Esbuild is an extremely fast JavaScript bundler and minifier that is designed to be a more modern alternative to existing tools like Webpack and Rollup. It is written in Golang and can be used to bundle JavaScript, TypeScript, and CSS code.

Vite serves source code over native ESM. This is essentially letting the browser take over part of the job of a bundler: Vite only needs to transform and serve source code on demand, as the browser requests it. The code behind conditional dynamic imports is only processed if used on the current screen.

Why use Vite over CRA?

We’ve gone through a few benefits in the previous section, so I will just highlight them here.

Quicker development server startup

Vite does not build the full application before serving, in contrast to CRA or bundler-based build setups. Dependencies and source code are the two categories that split the application components.

  1. Dependencies are plain JavaScript that does not change often during development (large component libraries like tailwind, mui, antd).
  2. Source code often contains non-plain JavaScript that needs transforming (e.g. JSX, CSS) and will be edited very often.
    Vite serves source code over native esm.

Less waiting time for reflecting file updates

File updates in CRA take longer as the codebase gets bigger. With Vite, this is not the case.

Let’s check out Vite’s approach to file updates.

  • In Vite, native ESM is replaced by hot module replacement (HMR). Vite invalidates the chain between an updated module and the nearest HMR boundary if a file is modified. Because of this, HMR updates are effortless and quick no matter how big your application is.
  • HTTP requests are used to retrieve modules. To speed up full-page reloads, Vite uses HTTP headers for caching. Requests for source code modules are made conditional via a 304 Not Modified response. Furthermore, requests for dependency modules are cached using Cache-Control: max-age=31536000, immutable.

Improved build performance

  1. Improved build performance: In real-world applications, Rollup often generates “common” chunks — code that is shared between two or more other chunks. Combined with dynamic imports, it is quite common to have the following scenario:

    Improve Build Performance
    As shown in the image in unoptimized scenarios, when async chunk A is imported, the browser does not know that it needs common chunk C without first requesting and parsing A. After figuring out that it needs common chunk C, the browser then imports it, leading to an extra network round trip.

  2. Entry ---> A ---> C

    Whereas, Vite rewrites code-split dynamic import calls with a preload step. When A is requested, C is fetched in parallel. This eliminates network round trips.

    Entry ---> (A + C)
  3. CSS code splitting: In an async chunk, Vite automatically separates the CSS used by the modules and creates a separate file for it. When the related async chunk loads, a link > element immediately loads the CSS file.

Prerequisites

Before using Vite, you’ll need a couple of prerequisites:

The third requirement is a browser that supports dynamic imports. You can check to see if your browser is supported by visiting: caniuse.com/es6-module-dynamic-import.

Most modern browsers are supported, if you’re on a somewhat recent version of Chrome, Edge, Safari, or Firefox, you should be all set.

Creating a React Project with Vite

To create a Vite application, open your terminal and navigate to the directory where you want to create the Vite project. Then, execute the following command:

npm :

npm create vite@lates

yarn ”

npm create vite@lates

Bun:

bun create vite

You can also directly specify the template you want to use and the project name in one single line:
npm create vite@latest my-react-app –template react

Note: You can customize the name of your Vite application to whatever you prefer. For example, if you want to name it “my-react-app”, you can replace it with your desired name.

Next, run the following commands in the terminal

cd my-react-app
npm install
npm run dev

Moving forward… After running the aforementioned command, the development server will initiate. Next, open your web browser and navigate to http://localhost:3000.

Comparison: Create React App (CRA) vs. Vite

Feature Create React App (CRA) Vite
Build Approach Builds the entire application before serving Builds the application on demand
ES Module Support Supports ES modules but doesn’t fully leverage their potentia Utilizes native ES modules
Bundling Technology Uses webpack for bundling Utilizes esbuild and Rollup for faster bundling
Hot Module Replacement Available but may have limitations Offers seamless HMR for faster development feedback
Plugin System Limited plugin system compared to Vite Supports a flexible plugin system
Optimization Optimization is handled through webpack configuration Employs built-in optimizations and modern bundling
Configuration Provides a pre-configured setup, limiting customization Offers more flexibility in configuration and customization
Development Server Uses webpack-dev-server for serving the application Employs a lightweight development server with fast reload time
Tree Shakin Supports tree shaking but may not be as efficient as Vite Utilizes advanced tree shaking techniques
Ecosystem Adoption Established and widely adopted in the React ecosystem Gaining popularity and traction due to performance benefits and modern approach

Conclusion

Vite revolutionizes frontend development by prioritizing native ES module support and rapid bundling through esbuild. Its advantages over Create React App (CRA) include faster development server initialization, minimized waiting periods for file updates, and enhanced build performance. Vite revolutionizes front-end development by prioritizing native ES module support and rapid bundling through esbuild. Its advantages over Create React App (CRA) include faster development server initialization, minimized waiting periods for file updates, and enhanced build performance.

Additionally, Vite offers features like CSS code splitting and comprehensive framework compatibility, ensuring a smooth development journey. For more details, visit Vite’s official website. Its user-friendly interface and efficiency position it as a premier option for contemporary web projects, surpassing conventional tools like CRA.

Femil Patodiya
Written By Femil Patodiya ReactJS Developer

Popular Categories

Get In Touch

Contact
GET IN TOUCH

Consult With Our Experts Today!

Your Benefits!

  • Professional Project Consultation
  • Detailed Project Proposal
Skype Skype Whatsapp WhatsApp