Every React app is unique, but they all begin with the same blueprint which requires:
An index.js, App.css and App.js file
A toolchain to use JSX
React and react-dom installed
A bundler to groups all your files into a single deployable file
We need this basic foundation.
Regardless, it is tedious to set this up for every project. You are in luck because Vite (pronounced “veet”) is here to save you the stress!
With one command executed in a few seconds, all the required tools and apps would be generated for you.
Also, Vite:
Enables Hot Module Replacement (HMR) which means that a live reload for your webpage is auto-enbled for real-time change.
Makes it easy to deploy your website to the internet
Helps you import and manage (potentially sensitive) environment variables
Makes it easy to bolt-on technologies needed like TypeScript
This is definitely something you need in your stockpile of developer tutorials.
In this article, I will show you:
How to scaffold your react app with Vite
How to enable HMR
How to deploy our app easily to a website called Netlify
What is the difference between Vite and Create React App (CRA)?
You should most likely recognize CRA if you are familiar with React and it would seem like Vite at first glance. It is not surprising to wonder how these tools compare considering that CRA is maintained by React.
CRA
About seven years ago, React designed and released CRA to help new developers in efficiency. Particularly, React acknowledged that to use JSX, you would need some toolchain and that made Reacts’ learning curve much steeper in comparison to a framework like Vue where you do not need a build tool.
More experienced developers use and appreciate CRA as well. Although, they need to use something else once their project becomes more complex.
Vite
The web has fundamentally evolved in the 7 years since CRA was designed.
According to the Vite documentation, "as we build more and more ambitious applications, the amount of JavaScript we are dealing with is also increasing dramatically. It is not uncommon for large-scale projects to contain thousands of modules."
Because the dependencies to make a React app have become so large and interconnected, tools like CRA can sometimes take an unreasonably long time to start up, and changes can take a couple of seconds to reflect on the webpage.
Vite points out, "The slow feedback loop can greatly affect developers' productivity and happiness."
In summary, React apps are becoming more complex, demanding more from our tools. Simultaneously, web browsers are evolving. For example, the latest browsers now support importing modules directly.
We can only benefit from these advancements if our tools are updated.
That is where Vite comes in.
Vite aims to leverage advancements in the ecosystem. Not only to make load-times quicker, but also to offer an instantaneous or nigh magical developer experience.
Unlike Create React App, Vite is not inherently coupled with React. You could use Vite with Vue for example.
While you might not plan to use another frontend library any time soon, open source maintainers banding together across the ecosystem will benefit you as more features make their way to releases and bugs are squashed more quickly.
Getting Started With Vite
Alright, now you know all about Vite (and how it compares to CRA), let's get hands-on.
In this section, I encourage you to follow along as we install Vite and set up a React project in no time.
To follow along, you would need to have npm installed. It would be good if you were already familiar with npm and command-line programs but it is not a requirement.
How to run Vite
The official way to run vite us to use the ‘npm create’ command. So, open your terminal, copy and paste the following command:
npm create vite@latest
Vite makes life easy by prompting you with questions like:
What your project name will be.
If you are using React or another library like Vue (remember, Vite is not limited to React.)
Here, I called my project ‘vite-app’ and chose react:
True to its name, Vite will quickly generate all the scaffolding for your project and some handy scripts to enable HMR.
Once the command has finished running, cd into your folder and run the following commands:
cd vite-app # Vite made a new folder named after your project
npm install
npm run dev
Since both npm create and npm install depend on your internet connection, they may take a minute or two to run.
Once everything is set up, look how quickly Vite served the app - just 5 seconds! That’s the magic of Vite!
Next, open localhost:5173 in your browser. You will see Vite's default template:
Of course you want to make some updates. Why not take advantage of HMR in the process?
What is HMR?
In the past, whenever you would make a change to your code, no matter how small, you would need to rebuild the entire app and refresh the page.
Rebuilding the entire app for one small change is slow.
Refreshing the browser isn't so bad, but you lose all the values in your variables (otherwise known as state) every time you do that.
Sometimes this is desirable, but it would be better if only the presentation parts changed when it comes to tweaking or iterating on your app (especially the style).
So, Enter HMR!
HMR intelligently rebuilds and reloads only the parts of your app that actually changed. It’s fast, and you keep your application state if you want.
HMR saves time you would otherwise spend waiting around or inputting data to recreate your application state. More than that, it reduces friction, allowing you to stay focused on your task and be more productive.
Test Vite HMR
Let’s take Vite’s built-in HMR for a spin.
Open src/App.js in your editor
Open localhost:5173 (ideally on the other side of your screen to observe the effect)
Increment the counter
Remove lines 10-17 from src/App.js (basically removing the two logos from the app)
If you opened your windows side by side, you should observe the following:
In my case, I increment the counter to 12 before removing the log
Usually, the page would reload, and the counter would be reduced to its default value of 0. HMR worked its magic behind the scenes to only change the part of the page that actually changed in the code.
Deploying your app to production
Vite makes it approachable to deploy your React website to Vercel, GitHub pages, or Netlify.
So approachable, I am encouraging you to follow along as we deploy the generated application to Netlify. When you make changes, updating the live website will be much easier then.
What do I need to know? To follow along, you will need: A GitHub account, Git installed locally, and fundamental knowledge of Git.
Start with Git
Nowadays, a practice called continuous deployment is common and encouraged.
In simple terms, when you push your code to the main branch on GitHub, services like Netlify detect this, download your updates, and update your live website. Vite can help accommodate this.
That might sound a bit mind-bending so I encourage you to try it for yourself. It will be much easier to understand when you see it all in action.
First up, create a GitHub repository and note the URL.
Next, run the following commands (making sure to replace with your repository URL!):
git init
git add .
git commit -m "Initial commit"
git branch -M main
git remote add origin <your_github_repository_url_goes_here>
git push -u origin main
Import project with Netlify
Great! You’ve made a GitHub repository and uploaded the code Vite generated there.
Next, we’ll let Netlify know about the GitHub repository.
If you haven’t already, this is a good time to make a free Netlify account.
Once you’ve logged in, click Add New Site, then Import Existing Project.
You will see the following page:
Click GitHub.
GitHub will ask if you want to give Netlify permissions to see your repositories and download them. You can go ahead!
Once Netlify has permission to interact with your GitHub account, it will load and list all your repositories. Pick the repository you just created. As you may recall, mine is called vite-app:
Deploy your app
Once you select your repository, you’ll be prompted to set some settings. Vite knows what Netlify wants to see and it makes your life easy by adhering to the defaults. That means you don’t have to change anything here. Just hit Deploy site:
Once deployed, you should see this page and the link to your website:
In our case, the link is resilient-gaufre-20030a.netlify.app:
When you next have some free time, poke around the Site Settings.
Here, you can change everything related to your site and even assign a custom domain name!
As you make changes to your code and push them to GitHub, Netlify should detect this and update the live site!
For more in-depth tutorials on deploying a Vite app to other hosting providers, you can visit Vite’s deploying a site section in its docs.
Advance Vite
Vite is built on the shoulders of giants - namely, Rollup and EsBuild:
Understanding how Vite works under the hood at the high level lends way to some advanced features you can take advantage of.
Plugins
Vite can be extended using plugins 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 extending the dev server and SSR functionality as needed.
In short, plugins let you do more with your site app by providing integrations with other tools and adding additional features on top of Vite to make development easier.
Vite has a very in-depth guide about plugins in its docs. You can read it to get started with plugins.
Env Variables
Env Variables are the variables set outside the code itself but are very important for the code to run and can't be leaked along with your code base.
They can be a token from an API you are using, Auth token, Database passwords, or anything that you wouldn’t want anyone else looking at your code to discover.
To set env variables, you create a .env file in the root of your application and then add your variables in the format TOKEN=secret_token, In most JavaScript applications you can access your env variables in code by using the process.env object.
Vite uses the object import.meta.env to expose your env variables, by default the env variables are not exposed to the frontend to prevent token leaking. To expose your variables to your code, you can prefix the variable name with VITE_.
# This will not be exposed to the frontend
SECRET_TOKEN=i_should_not_be_exposed_to_the_client
# This will be exposed to the frontend
VITE_NORMAL_TOKEN=i_can_be_exposed_to_the_client
# This will not be exposed to the frontend
SECRET_TOKEN=i_should_not_be_exposed_to_the_client
# This will be exposed to the frontend VITE_NORMAL_TOKEN=i_can_be_exposed_to_the_client
Now, to use these tokens in your code:
console.log(import.meta.env.SECRET_TOKEN)
console.log(import.meta.env.VITE_NORMAL_TOKEN)
There are some more concepts that you may need to know if you need more functionalities in your project like backend integration and server-side rendering but they are out of scope for this article.
The Verdict
According to npm, Vite is downloaded 1.4 million times a week, and that number is only going up! Perhaps now you’ve read this post, you can understand why!
In this post, we explored the fundamentals of Vite and how it compares to Create React App.
You got to experience first-hand how, when you start your project with Vite, it becomes somewhat straightforward to enable other productivity-boosting features like HMR, or even deploy your website to Netlify, for example.
Vite is easy because it hides a lot of the nitty-gritty details behind commands. Simultaneously, it’s still possible to drop down a level and take advantage of tried-and-true Rollup plugins. Looking back, it’s clear the Vite team observed developers in action to design and build a tool suitable for newer React developers and experts alike.