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

Dealing with the error "Type 'date[]' is not assignable to type '[date?, date?]' in a React hook

I'm attempting to assign a date range but encountering an error that states: Type 'Date[]' is not assignable to type '[Date?, Date?]'. Types of property 'length' are incompatible. Type 'number' is not assignab ...

Connect a click event from one component to another component

Can Angular bind a click event dynamically from a component to another existing component on the page? Check out this image for reference. In my app, I have 4 simple components - a shell component that defines the layout, a header component (blue outline) ...

What are the various methods of specifying function types in TypeScript?

I've noticed that in Typescript you can easily declare a function type using the declare keyword. For example: declare function test1(name: string): true const t1 = test1('t') // true Alternatively, you can also use the arrow notation: c ...

Converting PHP code to Typescript

Currently, I am working on developing a function for firebase that will trigger a POST request to call a specific URL. While I have successfully implemented GET requests, tackling the POST method has proven to be more challenging. I have some sample code ...

Generating custom error messages with specified format when utilizing routing-controllers

I'm currently working on a Node APP that utilizes the routing-controllers library. In the README file, there is a section titled Throw HTTP errors, which includes a self-explanatory example. However, I encountered an issue when attempting to replicat ...

MUI Autocomplete refuses to accept a value

In my Autocomplete feature, I have a list of all users available. When a user clicks on a button from another site, they are redirected to this site and the user's ID is fetched. I want the user with the corresponding ID to be automatically selected, ...

Trigger an event, pause, and subsequently trigger another one within Vue

I have successfully emitted the following events to the parent component: this.$emit('sendToParent1', true); this.$emit('sendToParent2'); this.$emit('sendToParent3'); this.$emit('sendToParent4', true); this.$emit(&ap ...

What's the best way to process a string array using iteration in Typescript?

I have an array of colors: colors = ['red','blue','purple']; I would like to display the following message: colors in ('red','blue','purple') When I tried to achieve this using forEach metho ...

Is it possible to optimize the performance of my React and TypeScript project with the help of webpack?

I am working on a massive project that takes 6 to 8 minutes to load when I run npm start. Is there a way to speed up the loading process by first displaying the sign-in page and then loading everything else? ...

Sending information from Vue to Express for processing

Is there a way to pass data from Vue to an express server? For example, in the scenario below, I am looking to send the data logged in my Vue function to the "id" variable on the server side. expressApp.post('/delete' , function (request, respons ...

What could be causing the 405 error in my post request?

While attempting to send a post request to Firebase through my Vue app, I keep encountering an error illustrated in this image. I have a webpack server running and the website is on localhost:8080. However, I also have a live version hosted on hostinger a ...

Using interfaces for typecasting in TypeScript

Consider the code snippet below: let x = { name: 'John', age: 30 } interface Employee { name:string, } let y:Employee = <Employee>x; console.log(y); //y still have the age property, why What is the reason for TypeScript ov ...

Using Vue JS to showcase array data in a dropdown menu with Bootstrap-vue

Currently, I have an array of JSON data structured like this: loggers = [{ "allAvailableLevel": ['WARN', 'DEBUG', 'INFO'], "level": "WARN", "logger": "com.test1", "status": "success" }, { ...

Can you clarify the meaning of "int" in this code snippet?

What does the ?: and <I extends any[] = any[]> signify in this context, and how is it utilized? export interface QueryConfig<I extends any[] = any[]> { name?: string; text: string; values?: I; types?: CustomTypesConfig; } ...

How can I pass a cookie token with axios?

Below is the code snippet I have developed to generate a token that will be returned as a cookie. public function authenticate(Request $request) { // extract credentials from the request $credentials = ['email'=>$request->header(& ...

When using Protractor with Typescript, you may encounter the error message "Failed: Cannot read property 'sendKeys' of undefined"

Having trouble creating Protractor JS spec files using TypeScript? Running into an error with the converted spec files? Error Message: Failed - calculator_1.calculator.prototype.getResult is not a function Check out the TypeScript files below: calculato ...

Implementing Jet Application Mark in Laravel version 8.x

As I was browsing through Laravel 8.x, I stumbled upon jet-application-mark which does not have an ending tag as expected for a Vue component... <div class="flex-shrink-0 flex items-center"> <a href="/dashboard"> ...

What is the reason behind continuously receiving the error message stating "Not all code paths return a value here"?

Can someone help me understand why I am consistently encountering this error message from typescript? PS. I am aware that in this scenario I could simply use a boolean and not create a function, but my focus here is on typescript. I keep receiving the er ...

Highlight dates in Vue.js that are overdue using a date filter

Currently, I have a Vue filter set up to display dates in a visually appealing way. However, I am looking to enhance the filter by adding a feature that would highlight dates in red if they are overdue (meaning the date is earlier than the current date). I ...

What is the best way to create a distinct slug using TypeScript and mongoose?

After scouring through numerous modules, I couldn't find one that worked with TypeScript, including mongoose-slug-generator and mongoose-slug-plugin. ...