tags:
by : Aashiya Mittal
May 26th 2023
Share

Vite, a rapid tool for project scaffolding and bundling – gains popularity with its speedy code compilation and instant module replacement. Discover Vite’s ultimate features while building your first App in this article.

With the availability of several tools and in the digital transformation era, every process has evolved. Then why not improve? We used to create projects with manual efforts of creating folders and transferring files using FTP.

Now developers have access to amazing tools and technologies to improve their development experiences, such as Babel and Webpack. But, to get along with changing business demands, we have to explore more new tools to deliver the best.

This brings our notice to a blazing-fast front-end development environment introduced in 2020. Since then it has gained much popularity and become the fastest tool for a seamless web development experience. Its features-rich CLI has made it easier for scaffolding projects.

But among the different options available in the market, why must developers choose Vite? What makes it more powerful and fast?

As we embark on this journey, we’ll delve into the realm of Vite and discover why it deserves our undivided attention. Let’s ensure we stay in sync with the ever-changing times and embrace this exciting new tool. So, without further ado, let’s dive into the world of Vite!

What is Vite?

Did you know that the word “Vite” comes from the French language and it means “quickly” or “fast”? Pronounced as “Vit,” this word perfectly captures the essence of what Evan You had in mind while working on Vue3, the popular JavaScript framework.

Vite is a revolutionary development environment for Vue.js, created by none other than Evan You himself. Its purpose is to make web development as fast as possible, pushing the boundaries of what we thought was achievable. Although still in the experimental phase, the community is actively working towards refining Vite, making it suitable for production environments.

What makes Vite so special is that it eliminates the need for a traditional bundler. Instead, it serves your code through native ES Module imports during development. This means that you can effortlessly work on Vue.js single file components without the hassle of bundling them together. However, Vite cleverly utilizes Rollup for efficient bundling when it comes to a production build.

With Vite, the possibilities for web development become endless. It empowers developers to focus on what truly matters—creating amazing experiences—without being hindered by time-consuming bundling processes. Evan You’s innovative creation is reshaping the way we approach Vue.js development, and the web development community is eagerly embracing this groundbreaking tool.

But do you wonder how it does it?

How did Vite come into the picture?

I guess without highlighting what crucial web development problems result in the development of this amazing front-end tool. Right! So what was the actual problem that developers have been facing before Vite?

The Problem

Before developers could leverage the ES modules within the browsers, there were no specific methods to author the JavaScript in a modular way. This is how the term “bundling” was introduced which uses the relevant tools to crawl, process, and connect different source modules within a single file to be run in the browser. 

If you are getting me, then you must know about the tools, such as webpack, Rollup, and Parcel. These tools are popularly known for their performance to improve the efficiency of developers in developing the front end. 

It is obvious that developers try to create more complex applications or apps get complicated with time, resulting in increased usage of JavaScript. If any JavaScript app scales, it will contain more modules that create performance nuances for JavaScript-based tools. 

It results in a long wait time to sign up into the related dev server, Hot Module Replacement, and to create/edit files in the browser. This slow speed was impacting the developer’s productivity. 

This is why developers need fast and extremely reliable front-end tooling.

Vite successfully addresses all these speed-related issues. All thanks to the availability of native ES modules in the browser, and the rise of JavaScript tools written in compile-to-native languages.

How does Vite work to deal with Slow Server Start?

Whenever you try to cold-start your dev server, your entire app will be crawled and built by a bundler-based build setup before serving it to the browser.

Vite is capable of improving and fastening the dev server start time. But how?

It divides the app modules into two categories- dependencies and source code.

  • Most JavaScript dependencies do not get impacted during the development process. So as the dependencies get larger, it will become a costly affair to process them. Also, the case is, that there could be multiple formats for dependencies, such as ESM or CommonJS. But Vite provides pre-bundled dependencies with the help of esbuild. As the esbuild dependencies are all written in the Go language, it will become 10-100 times faster to process them as compared to the JavaScript-based bundlers.

Vite.js esbuild

Image Credits- telerik

vite.js- bundle based dev server

Image Credit- craftsmenltd

  • In general, the source code has non-plain JavaScript that needs to be transformed and edited but not to be loaded all simultaneously. Vite serves the source code over native ESM, allowing the browser to take over the bundler’s job. Vite transforms and serves source code only if there is a demand, as the browser demands it. It will only process the code behind conditional dynamic imports if needed on the current screen.

Vite.js Native ESM dev server

Image Credit- craftsmenltd

How does Vite deal with slow Updates?

Editing files in a bundler-based build setup can be inefficient because rebuilding the entire bundle takes time, and the update speed slows down as the app size increases. Some bundlers use in-memory bundling during development, which means they only need to update a portion of the module graph when a file changes. However, they still have to reconstruct the entire bundle and reload the web page, which can be expensive and resets the application’s current state.

To address these limitations, bundlers offer Hot Module Replacement (HMR), allowing modules to be replaced without affecting the rest of the page. While HMR improves the developer experience (DX), it also suffers from decreasing update speeds as the application size grows.

Vite takes a different approach by using native ESM for HMR. When a file is edited, Vite only needs to invalidate the chain between the modified module and its closest HMR boundary, usually just the module itself. This ensures consistently fast HMR updates, regardless of your application’s size.

Additionally, Vite leverages HTTP headers to accelerate full-page reloads. It offloads work to the browser by making source code module requests conditional using “304 Not Modified” responses, and dependency module requests are efficiently cached with “Cache-Control: max-age=31536000, immutable” to avoid unnecessary server hits.

After experiencing the speed of Vite, it’s unlikely that you’ll be willing to tolerate bundled development again. So, let’s take a look at what features are being offered by mighty “Vite”.

Key Features- Vite

Below are the features that are the core behind the fast working of Vite.

  • Speedy compilation and HMR

Vite leverages cutting-edge browser technology and native ES modules to compile your code instantly, resulting in speedy builds and immediate updates within the browser. By eliminating the requirement for a bundler during development, Vite drastically reduces the time spent on building and deploying applications. 

Additionally, Vite’s built-in development server is optimized for quick reloading and hot module replacement, enabling developers to witness real-time changes to their code without refreshing the entire page. Get ready for a seamless and efficient development experience with Vite!

  • Lazy loading

Vite uses lazy loading for modules, loading code only when needed. This reduces bundle sizes and boosts performance, especially for bigger apps. It also speeds up initial load times by loading non-critical code on demand.

  • Tree-shaking and code-splitting

Vite optimizes code size and performance by tree-shaking and code splitting. Tree-shaking removes unused code, while code splitting divides code into smaller, on-demand chunks. Users download only necessary code, leading to faster load times and improved performance.

  • Built-in Development server

Vite has a built-in development server designed for fast reloading and hot module replacement. It simplifies application development and testing by enabling real-time code changes without refreshing the entire page. The server also supports automatic code reloading for rapid iteration.

The latest version of Vite 4.0 was introduced last year with a huge ecosystem.

According to the Jamstack Community Survey 2022, Vite usage has surged from 14% to 32%, maintaining a 9.7 satisfaction score. Vite’s popularity is spreading among developers, with renowned frameworks embracing its magic.

Features of Vite 4.0 (latest version)

Below are the features-

  • Play with vite.new
  • New React Plugin Using SWC
  • Browser Compatibility
  • Importing CSS as a String
  • Environment Variables
  • Patch-Package Support
  • Reduced Package Size
  • Vite Core Upgrades
  • update @types/node to v18
  • patch-package support
  • support multiline values in env files

To read about them in detail, you can check out their official news site.

Advantages of Vite

Below is the list of unwavering benefits of using Vite for your next project development.

Vite.js Advantages

  • Improve the development workflow

Vite’s unique front-end development enhances the developer experience. It offers speedy builds, real-time browser updates, and a built-in server with hot module replacement. This improves workflow, reduces manual testing, and enables focused coding.

  • Faster build times

By embracing an ingenious strategy, Vite eradicates the necessity for a bundler during development, leading to swift builds and instantaneous browser updates. This translates to precious time saved for developers, especially when working on extensive projects, empowering them to channel their energy into crafting top-notch code that delivers excellence.

  • Optimized codes

With Vite’s ingenious lazy loading of modules and cutting-edge tree-shaking features, developers can now achieve optimized code sizes like never before. Say goodbye to bloated applications and welcome lightning-fast performance for your users. 

This dynamic duo of features empowers developers to effortlessly shrink the size of their code, unlocking a world of enhanced performance and unrivalled user experience. From colossal projects to intricate applications brimming with modules, Vite swoops in to save the day, revolutionizing the way we build software. 

  • Improved productivity

A game-changer for developers, unlocking faster build times, an enhanced development journey, and optimized code sizes. With Vite, your productivity soars as you effortlessly create, iterate, and refine your applications. Harness its potential to accelerate your time to market, paving the way for a streamlined and efficient development process. Say goodbye to delays and hello to high-quality applications delivered swiftly by your dynamic team.

  • Compatible with modern web standards

Vite is perfect for developers who want to use the latest front-end standards. It uses native ES modules and modern browser APIs, ensuring modern, scalable code. This minimizes future updates and simplifies application maintenance.

Disadvantages of Vite

While Vite offers numerous advantages, it’s crucial to contemplate its drawbacks before opting for it. Here are the key disadvantages of Vite.

  • Limited community support

Due to its recent development, Vite has a smaller user community compared to established tools like Create React App or Webpack, making support and problem-solving challenging to find.

  • Limited compatibility with browsers

Vite, where we harness the full potential of modern JavaScript features. These innovative functionalities, however, are still on the rise and not universally supported by all browsers just yet. Thus, it’s important to note that while most users will enjoy a seamless experience with your application, a small portion might need to update their browser or utilize a clever polyfill to unlock its full glory. 

Vite vs. Create React App

Vite vs. CRA

When considering Vite and Create React App (CRA), it’s valuable to draw comparisons between the two, as they do share certain similarities. Interestingly, one of the primary motivations that drive developers towards Vite is their desire to break free from the confines of CRA.

Create React App, a widely embraced frontend tool, is renowned for its ability to construct web applications utilizing the powerful React JavaScript library. It presents an exceptionally smooth and efficient pathway for commencing React development, furnishing developers with a user-friendly command-line interface for effortlessly creating and managing projects. Moreover, it boasts a development server that facilitates live reloading, making the development process all the more seamless and dynamic.

Vite vs. CRA comparision table

Today, many companies are thinking of migrating their apps from Create React App to Vite due to the above benefits. 

How to Migrate CR apps to Vite?

Moving an existing React project to Vote can be a complex process. To avoid confusion, I’ll break down the steps. Start by deleting the node_modules folder to configure the package.json file for Vite. 

  • react-script dependencies from the  package.json file and add vite. Make sure to use the latest version of Vite.

Vite.js latest version

  • Then run npm install or yarm then change the scripts within the package.json file.

Replace scripts in package.json.

  • Always remember to Move public/index.html to index.html for Vite to work. Make changes to the index.html file as shown below.

remove all the %PUBLIC_URL% from index.html:

  • Now add an entry point in the above file.

Add entry point in index.html:

In case you are working with typescript, add a typescript entry point. 

  • Now, create a vite.config.js or vite.config.ts file at the project’s root.

create a vite.config.js or vite.config.ts file

For small projects, the above step works fine, but in the case of big projects, you need to follow the following steps also.

  • Manage env variables.

Below is the .env file.

manage dependencies

  • By default inVite, environment variables begin with “VITE_”. Therefore, any variables starting with “REACT_APP_” should be substituted with “VITE_”.

env_ex

  • Save your time in replacing all env variables, you can simply use a plugin “vite-plugin-env-compatible”. You must run the following.

npm i vite-plugin-env-compatible or yarn add vite-plugin-env-compatible.

Then add the following code to vite.config.js or vite.config.ts file.

vite-plugin-env-compatible

  • The envPrefix in Vite specifies the beginning of each environment variable, eliminating the need to modify their names. However, process.env should be replaced with import.meta.env, which can be done easily by searching and replacing in VSCode.

envPrefix

  • Manage additional configs

To enable TypeScript path aliases in Vite, install “vite-tsconfig-paths” and add it to your Vite config.

vite-tsconfig-paths

  • If you are using the “aws-amplify package” in your project for cognito authentication then you need to make changes to the vite config file and add “aws-amplify”.

aws-amplify

  • To enable TypeScript path aliases in Vite, install “vite-tsconfig-paths” and add it to your Vite config.

index.html file

  • Then add the below code to the index.html file within the script tag, as shown below.

edit index.html file

It allows Global to work anywhere within the project.

  • Finally, if you’re utilizing SVG files in your project, you can import them as React components in React using “import { ReactComponent as logo } from ‘your-svg-path””. However, this will cause an error in Vite. To resolve this, install “vite-plugin-svgr” via npm or yarn and add it to your Vite configuration file.

your-svg-path

To begin, navigate to your src folder and modify the vite-env.d.ts file by adding the following line: /// <reference types=”vite-plugin-svgr/client” /> (Remember to include the ///). Following this, the import {ReactComponent as logo} from ‘your-svg-path’ will function correctly.

This is the procedure for transitioning your existing project to Vite. Although it may require some time and exploration, once you have made the switch, you will significantly reduce the duration of your development server runs and file builds for the production server. 

You will be amazed to see the performance difference.

Build time using CRA:

CRA build time

Image Credits- semaphoreci

Build time using Vite:

Vite.js build time

Image Credits- semaphoreci

Seeing these amazing results, many companies are switching to Vite. 

Companies that have Migrated to Vite

Below are the companies that have leveraged the power of Vite for improved performance.

  • Replit: Replaced CRA with react starter templates to utilize Vite and enhance user experience.
  • Cypress: Incorporating Vite into their products.
  • Storybook: Starting Storybook 6.3 with Vite as a viable option for building Storybook.
  • Tailwind: Recognized Vite’s potential early on and sponsored the project. Introduced Just-in-Time Mode, which pairs well with Vite HMR for an improved experience.
  • Astro: Reworked their engine to utilize Vite, abandoning Snowpack.
  • Glitch: Using Vite for their starter projects.

If you are a new company or developer, who wants to create a Vite app from scratch, then we can help you understand how it works with the most simple example.

Build your first Vite app from scratch

Before you jump straight to coding. Make sure to have all the minimum prerequisites to build an app.

Basic app requirements

Once you have all the latest versions compatible with Vite 4, then follow the below steps to get started. 

  • Build React app with default template values.

npm init vite@latest first-vite-react-app –template react

Then select React Framework and JavaScript as a variant. 

  • After creating a project, go to the project folder.

cd first-vite-react-app

  •  Now, install all dependencies and start the development server using the below command.

npm install

npm run dev

  • Then open the local url on the browser to check the app working. You must see the below screen.

Understanding Vite Project Structure

The project structure is somehow similar to “Create React App” with minimal configs.

folder structure

Image Source- dev.to

  • Public directory: Contains static assets (favicon, robot.txt, etc.)
  • index.html: Entry point for the application, treated as source code by Vite.
  • main.tsx: Main file for rendering App.jsx (similar to index.js in creating react app).
  • src directory: Contains project source code.
  • vite.config.js: Defines configuration options (base URL, build directory, etc.).
  • package.json: Lists project dependencies (package names with versions).

Build blazing-fast Vite App with OnGraph

Some might find it difficult to transition/migrate their existing apps to Vite and to create an app from scratch even with sufficient knowledge.

If you are just beginning then you must take help from experts who can help build potential solutions. We have a team of experts who are capable of smooth app migration and building completely new solutions for your business to scale.

Let’s schedule a call with OnGraph along with requirements and we will build a next-gen Vite app for you.

 

ABOUT THE AUTHOR

Aashiya Mittal

A computer science engineer with great ability and understanding of programming languages. Have been in the writing world for more than 4 years and creating valuable content for all tech stacks.

Latest Blog

Full-Stack vs MEAN Stack vs MERN Stack

Full-Stack vs MEAN Stack vs MERN Stack: The Right Technology Stack For You In 2024

Read more
On Premise vs Cloud

On Premise vs Cloud Benefits, Risk

Read more
Create A Dating App For Free

How To Create A Dating App For Free? Understanding Benefits, Cost, Development, Process and Benefits

Read more