Editor’s note: This tutorial on building a TypeScript app with Vite was last updated on 21 July 2023 to verify accuracy and to add a section on the benefits of using Vite for React apps.
React, combined with TypeScript, offers a powerful way to develop scalable and maintainable web applications. TypeScript brings static typing to the world of JavaScript, making it easier to write error-free code. Meanwhile, Vite is a fast and lightweight build tool for modern web development, providing a rapid development experience focused on speed and simplicity.
In this article, we’ll delve deep into how to harness the combined strengths of React, TypeScript, and Vite to create an efficient web application. We’ll walk through the process of initiating a new project, integrating TypeScript, setting up React, and utilizing Vite’s capabilities to enhance the development experience.
Whether you’re a seasoned web developer or just starting out, I think you’ll find this article valuable. So grab a cup of coffee and let’s get started!
Vite offers many unique features that set it apart from other build tools and make it an excellent choice for web development. Let’s take a look at some of Vite’s special features:
TypeScript and Vite are two powerful tools that have gained widespread popularity in the web development community. While TypeScript provides type safety and a strong foundation for building scalable applications, Vite offers a fast and efficient development experience. So, why combine these two technologies? Let’s take a look.
Vite offers a unique development experience due to its speed, efficiency, and compatibility with modern JavaScript libraries like React. Here are some specific benefits when using React with Vite:
Now that we understand more about the powerful combination of TypeScript and Vite, let’s dive into the demo portion of this tutorial.
First, ensure that you have Node.js ≥v18 installed on your machine, then create a Vite project by running the following command in the terminal:
npm create vite@latest
This command will prompt you to choose a name for your project. Feel free to choose any name; then press Enter to continue. For this demonstration, we’ll use the project name vite-ts-app
.
Next, you’ll be asked to select a framework for your Vite project. Vite provides a variety of frameworks that may be used for an application: React, Vue.js, Lit, Preact, vanilla JavaScript, and Svelte. For this demo, we’ll select React.
Lastly, you’ll be prompted to choose a variant for your application. For this demo, we’re building a TypeScript app with Vite, so we’ll select TypeScript.
Here are our selections for the Vite project prompts:
After processing the project information we just submitted, Vite will generate the project’s folder structure:
📦vite-ts-app ┣ 📂public ┃ ┗ 📜vite.svg ┣ 📂src ┃ ┣ 📂assets ┃ ┃ ┗ 📜react.svg ┃ ┣ 📜App.css ┃ ┣ 📜App.tsx ┃ ┣ 📜index.css ┃ ┣ 📜main.tsx ┃ ┗ 📜vite-env.d.ts ┣ 📜.gitignore ┣ 📜index.html ┣ 📜package-lock.json ┣ 📜package.json ┣ 📜tsconfig.json ┣ 📜tsconfig.node.json ┗ 📜vite.config.ts
Below are the key files from the vite-ts-app
project folder:
index.html
: The main file, typically found in a public directory in a Vite projectmain.tsx
: Where the code for producing the browser output is executed. This file is common for Vite projectsvite.config.json
: The configuration file for any Vite projectWe’ve completed the prompts to create a Vite project. Now, let’s cd into the project folder and use the below commands to run the application:
cd vite-ts-app npm install npm run dev
To confirm that the application is running, check the terminal — and you should see the following:
Press the o
key to open the application in your web browser:
With the Vite app up and running in our browser, let’s create a blog application using Vite and React that renders some static blog data from a JSON file.
To get started, let’s update the code in the App.tsx
file to add a navbar to the application’s UI:
import './App.css' function App() { return ( <div className="App"> <div className="navbar"> <ul> <li>Home</li> <li>Blog</li> </ul> </div> </div> ) } export default App
Next, let’s update the App.css
file to add some new styles to the application:
* { padding: 0px; margin: 0px; box-sizing: border-box; } .navbar { background-color: rgb(50, 47, 47); color: white; padding: 10px; } .navbar ul { display: flex; width: 600px; margin: 0px auto; font-size: 14px; list-style: none; } .navbar ul li { margin: 10px; }
The resulting UI will look like the following:
Next, we’ll need to add data to our blog application. Let’s create a blog.json
file in the project’s root directory and add the following data:
[ { "id": 1, "title": "Building a Todo App with Vue", "cover": "https://nextjs.org/static/images/learn/foundations/next-app.png", "author":"John Doe" }, { "id": 2, "title": "Getting started with TypeScript", "cover": "https://nextjs.org/static/images/learn/foundations/components.png", "author":"Claman Joe" } ]
Here we defined some arrays of blog objects, which we’ll render in our Vite app’s UI.
Now, let’s create a components
folder in the src
directory. Then, we’ll create a Blog.tsx
file and add the below snippet:
import blogData from '../../blog.json' type Blog = { id: number, title: string, cover: string, author: string } export function Blog() { return ( <div className="container"> <div className="blog"> {blogData.map((blog: Blog) => <div className="card" key={blog.id}> <img src={blog.cover} alt="" /> <div className="details"> <h2>{blog.title}</h2> <h4>{blog.author}</h4> </div> </div> )} </div> </div> ) }
This code defines a function that returns a container for blog posts and includes a list of blog cards. Each card displays the title, cover image, and blog post author. The code uses a map
function to loop through a blogData
array and create a card
for each item.
Next, let’s update the App.css
file to style the Blog
component:
.App { background: rgb(44, 183, 134); height: 100vh; } .container { width: 600px; margin: 0px auto; } .container .blog { display: flex; padding: 10px; } .container .card { background-color: white; margin: 10px; padding: 10px; border-radius: 4px; width: 50%; font-size: 10px; color: rgb(50, 47, 47); } .container .card img { width: 100%; }
Lastly, let’s update the App.tsx
component to import and render the Blog
component:
import './App.css' import { Blog} from './components/Blog' function App() { return ( <div className="App"> <div className="navbar"> <ul> <li>Home</li> <li>Blog</li> </ul> </div> <Blog /> </div> ) } export default App
And with that, we’ve successfully created a blog application using TypeScript and Vite! If all went well, it should look like the image below:
To compare the startup time of a Vite app to an app built with an alternative like Create React App (CRA), we’d need to build and test both apps under similar conditions. To demonstrate this, I built the same demo application that we just created in this tutorial, except I used CRA. Then, I used the performance inspection feature in Chrome DevTools to test the start time for each version of the app.
Here’s the performance result for the TypeScript app built with CRA; the startup time was 99ms:
And here’s the performance of the TypeScript app built with Vite; the startup time was 42ms:
In our test, the TypeScript application built with Vite started 58 percent faster than the TypeScript application built with Create React App.
In this article, we discussed the many benefits of combining React, TypeScript, and Vite, demonstrated how to build a simple React-based blog application using TypeScript and Vite, and then compared the performance of our app with that of a TypeScript app built with Create React App.
The fusion of React, TypeScript, and Vite presents an array of benefits for web developers — from React’s component-based approach and TypeScript’s enhanced type safety to Vite’s rapid development experience. This blend promotes scalable, maintainable code and superior performance.
Vite’s focus on speed, efficiency, and simplicity helps deliver high-quality, performant web applications. The combination of TypeScript and Vite affords developers of all levels an excellent choice for building high-quality and performant web applications.
I hope you got value from this tutorial. Happy coding!
LogRocket is a frontend application monitoring solution that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.
In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page and mobile apps.
Install LogRocket via npm or script tag. LogRocket.init()
must be called client-side, not
server-side
$ npm i --save logrocket // Code: import LogRocket from 'logrocket'; LogRocket.init('app/id');
// Add to your HTML: <script src="https://cdn.lr-ingest.com/LogRocket.min.js"></script> <script>window.LogRocket && window.LogRocket.init('app/id');</script>
Would you be interested in joining LogRocket's developer community?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowBuild scalable admin dashboards with Filament and Laravel using Form Builder, Notifications, and Actions for clean, interactive panels.
Break down the parts of a URL and explore APIs for working with them in JavaScript, parsing them, building query strings, checking their validity, etc.
In this guide, explore lazy loading and error loading as two techniques for fetching data in React apps.
Deno is a popular JavaScript runtime, and it recently launched version 2.0 with several new features, bug fixes, and improvements […]
One Reply to "How to build a React + TypeScript app with Vite"
so… you show a tutorial on using vite – however you fail to show the vite config file