Open In App

How to Use TypeScript with Vite?

Last Updated : 06 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Vite is a modern build tool known for its speed and efficiency. Using TypeScript with Vite combines Vite's fast development experience with TypeScript's strong static typing, enabling early error detection and more maintainable code. This integration enhances productivity and code quality in modern web development.

Prerequisites

Approach

We have discussed below how to use TypeScript with Vite, we make sure that Nodejs is installed in our system or not if not then we will install that first, which will create a new Vite project using the terminal writing the command after that we will select the TypeScript framework then select the variant then the last step is to install all the dependencies.

Steps to Use TypeScript with Vite

Step 1: Install NodeJs, If you haven’t installed NodeJs, download it from the official website.

Step 2: Create a new Vite Project

npm create vite@latest my-react-app --template react-ts

Step 3: Select a framework: select the React framework here using the downward arrow key.

Vanilla
Vue
React
Preact
Lit
Svelte
Solid
Qwik
Others
OP1
select React

Step 4: Select Variant: choose any variant of your choice using the downward arrow key,i.e: choose TypeScript

TypeScript
TypeScript + SWC
JavaScript
JavaScript + SWC
OP2
select Typescript

Step 5: Now, switch to my-react-app directory

cd my-react-app
OP3
Naviagate to the directory

Step 6: Install Dependencies

npm install

package.json:

"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0"
}

Step 7: Start Server, make sure check your port no on the terminal it may be different for you system.

  ➜  Local:   http://localhost:5173/

Project Structure:

PS
Project structure

Example: We are using TypeScript with Vite to create a React component that shows handling arrays and objects with type safety. The App component displays a list of hobbies and a list of people, each with specified types, using TypeScript interfaces and array methods to render the content dynamically.

CSS
/** App.css **/
#root {
  max-width: 1280px;
  margin: 0 auto;
  padding: 2rem;
  text-align: center;
}

.logo {
  height: 6em;
  padding: 1.5em;
  will-change: filter;
  transition: filter 300ms;
}
.logo:hover {
  filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.react:hover {
  filter: drop-shadow(0 0 2em #61dafbaa);
}

@keyframes logo-spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

@media (prefers-reduced-motion: no-preference) {
  a:nth-of-type(2) .logo {
    animation: logo-spin infinite 20s linear;
  }
}

.card {
  padding: 2em;
}

.read-the-docs {
  color: #888;
}
JavaScript

Output: To run the application use npm run dev into the terminal.

OP4
Output

Similar Reads

three90RightbarBannerImg