Adding TypeScript to your Vue 3 and Vite project: A step-by-step guide

After setting up my project by installing Vue and Vite using the create-vite-app module, I decided to update all the packages generated by 'init vite-app' to the latest RC versions for both Vue and Vite.

Now, I am interested in using TypeScript for my code. To test it out, I added the attribute lang="ts" to the tag in HelloWorld.vue, and surprisingly it worked without any issues. However, I'm uncertain about how TypeScript is transpiled from a Vue file.

Next, I attempted to change the filename main.js to main.ts, but nothing seemed to happen. This got me thinking whether simply installing TypeScript would solve the issue.

Despite my confusion, I couldn't help but wonder why TypeScript was functioning within the Vue component (HelloWorld) while no JavaScript was being generated from the *.ts file.

Answer №1

Adding TypeScript to Your Vue 3 and Vite Project

Here is a step-by-step guide to incorporating TypeScript into your Vite project:

  • To begin, create a new Vite project:
$ npm init vite-app <project-name>
$ cd <project-name>
$ npm install
  • Next, install TypeScript:
$ npm install typescript
  • Then, create a tsconfig.json file in the root directory with these settings:
{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "moduleResolution": "node",
    "importHelpers": true,
    "isolatedModules": true,
    "noEmit": true
  }
}

For more information on tsconfig.json, visit here.

  • After that, create a shims-vue.d.tsfile in the src folder like this:
declare module "*.vue" {
  import { defineComponent } from "vue";
  const Component: ReturnType<typeof defineComponent>;
  export default Component;
}

The shims-vue.d.ts file helps IDEs understand files ending in .vue.
Now, test if .ts files work by renaming main.js to main.ts in the src folder
and updating line 12 of index.html:

 <script type="module" src="/src/main.js"></script> 

to

 <script type="module" src="/src/main.ts"></script> 

Finally, run:

npm run dev

If there are no errors, you can start creating components using .ts files.
Good luck!

Answer №2

Have you heard of the typescript template called vue-ts? When you run

npm init vite@latest my-vue-app -- --template vue-ts
, it will help you set up a typescript vite project.

Check out this link for more information: https://vitejs.dev/guide/#scaffolding-your-first-vite-project

UPDATE: Taking into account Olanrewaju's comment.

Answer №3

According to the most recent documentation, there are several commands available for selecting a framework and typescript options:

npm init vite@latest

yarn create vite

pnpm dlx create-vite

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Bring in dynamic Pinia store and Vue component that rely on a particular reference

Currently, I am in the process of developing an application using Quasa V2 framework, vue, vite, pinia, and format. One of the components in my app is basicList.vue, which retrieves its control attributes and properties from a pinia store named oTable. By ...

Tips for conducting tests on ngrx/effects using Jasmine and Karma with Angular 5 and ngrx 5

Here is the file that I need to test. My current focus is on some effects service while working with Angular5 (^5.2.0) and ngrx5 (^5.2.0). I have been struggling to properly implement the code below for testing purposes. Any tips or suggestions would be ...

Is there a way to trigger a request to the backend when the user closes or refreshes the browser?

My Objective: I am working on a lobby feature that updates automatically when a player leaves. Using backend requests and sockets, the lobby is updated to display the current list of players after someone exits. The Challenge: I am faced with the issue ...

How to efficiently fetch Redux state through reducers with an action-based approach

Utilizing Redux actions to manage a list of contacts, I am facing an issue where I am unable to retrieve the actual state contact. Despite setting the contact in the action, all I receive is the contact set within the action itself. Can someone guide me on ...

Guide to setting up identically named properties in Child container components

As I am still fairly new to React and its concepts, I may not be executing this correctly. Although the question might seem lengthy, I'll try my best to keep it simple. I have created a component for TableHead that extends some material-ui components ...

What types of elements can a v-bind:is directive display?

One of the challenges I am facing involves a component that registers over 15 external components. Within the template, there is a dynamic component implemented as follows: <template> <component :is="config.name" /> </template> ...

The panning functionality on Android devices within the Firefox browser is currently experiencing issues with both panstart and pan

Currently, I am collaborating on an Angular7 project and utilizing hammerjs version 2.0.1. One of the tasks at hand is to allow panning functionality on a map for mobile devices. After testing on various android devices, I noticed that it performs well on ...

Combining Django, Graphene, Apollo, django-webpack-loader, and Vue: Struggling with CORS and CSRF compatibility issues?

Currently, I am immersed in a project that involves Django as the backend, Vue as the frontend, and Apollo/Graphene/GraphQL as the data transfer layer. While most of it is functioning smoothly, I am encountering difficulties with the CORS/CSRF settings. I ...

Finding the index of a chosen option in Angular

Attempting to retrieve the index of the selected option from a select element using Angular. The Angular (4) and Ionic 3 frameworks are being utilized. The template structure is as follows: <ion-select [(ngModel)]="obj.city"> <ion-option ...

Tips for customizing the main select all checkbox in Material-UI React data grid

Utilizing a data grid with multiple selection in Material UI React, I have styled the headings with a dark background color and light text color. To maintain consistency, I also want to apply the same styling to the select all checkbox at the top. Althou ...

What is the process for configuring a TimePicker object in antd to send a Date with UTC+3 applied?

I have Form.Item and a TimePicker defined inside it. I am using this form to send a POST request, but when I try to post 16:35, it gets sent as 13:35. The UTC offset is not being considered. However, the CreationTime works fine because it utilizes the Da ...

There is an issue with the Angular Delete request functionality, however, Postman appears to be

HttpService delete<T>(url: string): Observable<T> { return this.httpClient.delete<T>(`${url}`); } SettingsService deleteTeamMember(companyId: number, userId: number): Observable<void> { return this.httpService.delete< ...

The Angular directive ng-if does not function properly when trying to evaluate if array[0] is equal to the string value 'Value'

In my code, I want to ensure that the icon is only visible if the value at array index 0 is equal to 'Value': HTML <ion-icon *ngIf="allFamily[0] === 'Value'" class="checkas" name="checkmark"></ion-icon> TS allFamily = [ ...

Tips for sending a query using the http GET method in Next.JS 14 API routes

When using the Next.js 14 API route, I am passing a page in the GET method to paginate the data fetched from my database. However, an error is thrown when trying to retrieve the query from the request: Property 'query' does not exist on type &a ...

Can you explain the meaning of the code `@input="$emit('input', $event)" used in a Vue component?

I have come across some code that I am looking to revise: <b-input :value="value" @input="$emit('input', $event)" ref="input" :maxlength="maxlength"/> Can someone explain what @input="$emit('input', $event)" means? Where should ...

Tips for ensuring session token verification remains intact upon reloading

I am currently in the process of developing a website using the Next.js framework and I am seeking advice on how to prevent the reload effect that occurs when transitioning from the login page back to the main page for just a fraction of a second. Below i ...

Ionic 3 Storage Timing Explained

I have a scenario where I am trying to load JSON data from storage and display it on the HTML template of my page. However, when I try to do this, I encounter errors suggesting that the information is not yet available upon entering the page. I'm sta ...

Tips for handling Vue/Axios JSON payload sent data in Yii2

After spending some time trying to figure it out, I finally realized the solution, which was a bit obvious. I am sharing my answer here so that others can benefit from it and also to see if there is a more efficient way to handle this issue. The problem I ...

Navigating through a large set of data in a web application can be challenging, but with the async await function

I have been working on an app that utilizes the GitHub API to display a user's repositories from Github. However, I am facing a challenge in fetching data from all pages as I can currently only retrieve repositories from one page. I attempted to addre ...

The Nuxt3 application is experiencing technical issues when running in production

My app performs well in development mode when using "npm run dev". However, once I build it with "npm run build" and then launch it with "npm run start", it starts to malfunction. Specifically, the dynamic styles that control whether a button should be d ...