How to Build Web Apps Using Vite
How to Build Web Apps Using Vite
Getting started with Vite
In this article, we will useViteto bundle an existingweb app. Vite may be the right build tool for you if your project contains many modules as it can bundle files at lightning speed bypre-bundling dependencies.
Vite makes it easy to start a project as it comes withtemplate presetsfor projects using vanillaJavaScript (JS), as well asframeworkssuch as Vue,React, Preact, Svelte, andTypeScript. Vite also providesHot Module Replacement, which is automatically configured when a project is created usingcreate-vite. The functionalities of Vite can be easily extended by usingplugins.
You can follow along with your own project or downloadthis simple React appfor a photo carousel.
Let’s get started!
Setting up the project
If you are following along with your own project, make sure it is aNode.jsproject. Remember that you can initialize Node.js using:
npm init -y
Copy to clipboard
npm init -y
If you are following along using the provided React app, the project is already a Node.js project. But you will need to install the dependencies that are in thepackage.jsonfile by running the following command:
npm install
Copy to clipboard
npm install
Next, you will need to install Vite as well asreact-refreshto add HMR support by running:
npm install vite @vitejs/plugin-react-refresh
Copy to clipboard
npm install vite @vitejs/plugin-react-refresh
Configuring Vite withvite.config.js
In order to properly use Vite, you will need to create avite.config.jsfile in the root of your project. This file will contain the configuration for your project, including any additional plugins that your project may require.
Add the following code to yourvite.config.jsfile:
import { defineConfig } from 'vite';import reactRefresh from '@vitejs/plugin-react-refresh';
export default defineConfig({ plugins: [reactRefresh()]});
Copy to clipboard
import { defineConfig } from 'vite';import reactRefresh from '@vitejs/plugin-react-refresh';
export default defineConfig({ plugins: [reactRefresh()]});
In the configuration file, we are using a plugin calledreact-refresh()from@vitejs/plugin-react-refresh. This plugin will be used to refresh the page when you make a change to a react component.
Addingbuildandservecommands
Let’s add ourstart,build, andservecommands in the"scripts"section ofpackage.json. These commands are used to do either of the following:
- Serve a development build of our app.
- Build a production build.
- Serve the production build of our app locally.
"scripts": { "start": "vite", "build": "vite build", "serve": "vite preview"}
Copy to clipboard
"scripts": { "start": "vite", "build": "vite build", "serve": "vite preview"}
In the code block above, thebuildcommand runs with the default entry point at./index.htmlto bundle the app with the exit point at./dist. After running theservecommand, the project is served from./dist.
Remember that you can run thebuild,start, orservecommands withnpm run X, whereXis our custom script.
If you are following along with the starting code of our React app, you will notice that runningnpm run startwill produce the following error:
> src/app.js:31:11: error: Unexpected "<" 31 │ return <Carousel src={PATHS[currentImg]} /> ╵ ^
Copy to clipboard
> src/app.js:31:11: error: Unexpected "<" 31 │ return <Carousel src={PATHS[currentImg]} /> ╵ ^
This error is caused by Vite encounteringJSXcode in a JS file. We will address this in the next section.
Fixing JSX errors in Vite
Our scripts will throw errors because ourCarousel.jsfile contains JSX. While this is supported in Vite, JSX files must have the.jsxextension. If you are following along using the provided starting code, you will need to change the file extension of bothApp.jsandCarousel.jstoApp.jsxandCarousel.jsx, respectively.
The file structure of./srcshould now look like this:
|-- src
| |-- app.jsx
| |-- Carousel.CSS
| |-- Carousel.jsx
| |-- sun.svg
You will also need to edit the value of thesrcattribute of the opening<script>tag in./index.htmlfrom'/src/app.js'to'/src/app.jsx'to reflect the change in file extension.
<script type="module" src="/src/app.jsx"></script>
Copy to clipboard
<script type="module" src="/src/app.jsx"></script>
Handling CSS with Vite
WhenCSSfiles are imported directly in JS using theimportstatement, Vite will automatically gather all referenced CSS files and bundle them into a single CSS file at the exit point.
You will see that in the provided starting code we importCarousel.cssinCarousel.jslike below:
import './Carousel.css';
Copy to clipboard
import './Carousel.css';
Vite doesn’t need any plugins or config options specified in order to automatically bundleCarousel.cssfile at the exit point at./dist.
Running the Vite app
Now that we’ve configured ourvite.config.jsfile, file extensions, andpackage.json, running thebuildcommand should generate bundled files of the project in./dist. Notice that the files in thesrcdirectory have been bundled and linked in./dist/index.html.
To view the bundled app in./dist, you will need to run:
npm run serve
Copy to clipboard
npm run serve
In this article, we discussed how to use Vite to quickly build your application and utilize its extensive plugin system. Next time you’re building a web app on your own, consider using Vite!
Conclusion
Vite is a powerful and efficient build tool that simplifies web app development with features like fast bundling, Hot Module Replacement, and built-in support for various frameworks. By following this guide, you can set up, configure, and optimize your project seamlessly. Next time you start a new web app, consider using Vite for a smoother development experience!
To further enhance your understanding of Vite and modern build tools, consider exploring Codecademy’sLearn Build Toolscourse.
'The Codecademy Team, composed of experienced educators and tech experts, is dedicated to making tech skills accessible to all. We empower learners worldwide with expert-reviewed content that develops and enhances the technical skills needed to advance and succeed in their careers.'
Complete Payment to Unlock Full Guide & Source Code
You are viewing the 30% preview. Join TopCourseAI Pro to unlock the remaining 70% of this article, unblur all code snippets, and gain full access to all 412 technical projects and guides.
Ready to access the complete step-by-step tutorial?
Gain full unhindered access to all 412 technical projects and guides, unblur all source code snippets, and download runnable scripts.
How to Build RAG Pipelines in AI Applications?
Next BlueprintHow to Build a Smart Q&A Bot with Haystack: RAG Made Easy
Related Blueprints & Guides
View all 166 →Accessibility on the Platform
Codecademy is committed to providing a high-quality learning experience for all learners. That includes accommodating different usage forms such as auditory, motor, or visual restrictions, limited hardware, or other acce...
Web developmentAffordances, Signifiers, and Clickability
For users on the web, the mouse click is perhaps the most fundamental human-computer interaction. The webbecamethe web partially through the power ofhypertext, or text in one document that links to other documents or res...
Web developmentAuthentication and OAuth
Authenticationis the process used by applications to determine and confirm identities of users. It ensures that the correct content is shown to users. More importantly, it ensures that incorrect content is secured and u...
Ready to build production-grade AI systems?
Enjoyed this guide? Continue exploring our library of 166+ production blueprints, multi-agent swarms, and autonomous agent systems with 100% unblurred, executable source code.