Tips for leveraging Typescript in .vue files utilizing VS Code?

I have set up my development environment using Visual Studio Code, Vue 2 (webpack template), and Typescript.

Below is the code snippet for my App.vue component:

<template>
    <div id="app">
        <navbar></navbar>
        [content here]
    </div>
</template>

<script lang="ts">
    import Navbar from './components/Navbar'

    export default {
        components: {
            Navbar
        }
    }
</script>

Question 1: Everything is functioning correctly, but I am looking to enable intellisense within the <script lang="ts"> tag similar to .ts files. How can this be accomplished?

Question 2: In my main.ts file, I use import App from './App'. However, VS Code highlights "./App" in red as it cannot locate the .ts file. Is there a way to make the editor recognize .vue files before compilation (during editing)?

Update (2018-03-25): For those interested in setting up Typescript in a Vue project, I highly recommend reading this article.

Answer №1

To address Q1, place the Typescript code in a separate file named script.ts and include it in the App.vue file as shown below:

<script lang="ts">
   import s from './script'
   export default s
</script>

Regarding Q2, as suggested by user @Oswaldo, you can create a file named vue.d.ts with the following content:

declare module '*.vue' {
  import Vue = require('vue')
  const value: Vue.ComponentOptions<Vue>
  export default value
}

If you save this file in the ${Project_ROOT}/typings directory, make sure to add it to your tsconfig.json like so:

"typeRoots": ["./typings"]

Now, you can import files ending with .vue using the proper syntax:

import App from './App.vue'

If you prefer not using the .vue extension, organize all Vue components in a specific folder like src/components and adjust the vue.d.ts accordingly:

declare module 'src/components/*' {
  import Vue = require('vue')
  const value: Vue.ComponentOptions<Vue>
  export default value
} 

The alias src is set in webpack.base.conf.js to represent an absolute path.

resolve: {
  extensions: ['.js', '.vue', '.json', '.ts'],
  alias: {
    'vue$': 'vue/dist/vue.esm.js',
    'src': resolve('src')
  }
}

After making these adjustments, use the full path to import a component without the need for the .vue extension:

import App from 'src/components/App'

While these solutions may not be the most elegant, they effectively eliminate any red underlines that are present.

Answer №2

Regarding question 2, vue-class-component provides a solution through its sfc.d.ts file. I hope this proves helpful to you. If you have any insights on question 1, please do share them with me.

Answer №3

When exploring Q1, I discovered a useful VS Code extension titled vetur that provides intellisense support.

In relation to Q2, the solution cannot be implemented using .vue files; instead, one must utilize .ts files with a template embedded within.

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

Scroll effortlessly to the middle, bottom, and top of the page in vue.js using arrow keys for a seamless

I'm interested in implementing a feature that allows users to scroll smoothly up and down the page using the arrow keys. When the first down key is pressed, I'd like to smoothly scroll to the middle (50%) of the page, and when the second down ...

Nuxt Fire / Firebase Vuex does not recognize $fireDb

Currently, I am utilizing Nuxt JS 2.9.2 for constructing a Javascript application. The application incorporates Firebase integration through the Nuxt Fire module, as well as Vuex for managing state and authentication. The project has been successfully con ...

How can I ensure that TypeORM, Type GraphQL, Apollo Server, and Azure Functions work together seamlessly?

I have an Azure Function written in TypeScript that utilizes various technologies such as TypeORM, Apollo Server, and TypeGraphQL. The function involves creating resolvers for projects and tasks and establishing a database connection. import { createConne ...

VSCode Troubleshooting: When TypeScript Doesn't Recognize Installed Libraries

Lately, I've encountered a problem when using TypeScript in VSCode. Whenever I install a new library through npm, TypeScript doesn't seem to acknowledge the library right away. For instance, after adding the query-string library and attempting to ...

Importing an anonymous ES5 function using Typescript

I am currently facing an issue with ES6 import syntax when importing a third-party ES5 module that only exports a single unnamed function: module.exports = function (phrase, inject, callback) { ... } Since there is no default export and just an anonymous ...

Remove focus from input field after submitting in a project using Typescript and React with react-hook-form

I'm currently working on a TS-React project and encountering an issue with barcode scanning in my inputs. I am using react-hook-form along with the useForm Hook. The form consists of one input-text field and a submit button, both within a global form. ...

What is causing me to receive an array filled with null values instead of an array with zeros?

In my Vue 3 code, I have implemented the following logic: const salesTotal = computed(() => { let totalSalesAmount = new Array(numberOfPeriods).fill(0); return totalSalesAmount; }); const cogsTotal = computed(() => { le ...

Utilizing an Angular Service within a method, embedded in a class, nested inside a module

module Helper { export class ListController { static handleBatchDelete(data) { // Implementing $http functionality within Angular ... $http.post(data) } } } // Trigger on button click Helper.ListController. ...

Animating nested child routes with framer-motion in react-router-dom version 6.4.3



I recently updated to the latest version of react-router-dom and their new Data APIs, which required me to rewrite my app's routing logic using object-based routing instead of the V5 JSX syntax with Routes. I'm curious if anyone has been su ...

What is the best way to connect a router link and dialog box in a dropdown menu using Vue.js?

https://i.sstatic.net/JahMG.pngI am working on implementing a dropdown menu that includes a router link to another component and a dialog component for a dialog box. Here is the code snippet for reference: <td align="center"> <v-btn ...

Leverage i18n capabilities by integrating with data sourced from the Wordpress RestAPI

I've been struggling with this problem for a while now and I can't seem to find any answers or people who have faced the same issue. Also, English is not my first language and I'm new to programming, so please forgive me if my approach se ...

Utilizing various filters and sorting options on API response within Angular 8

Upon receiving the following API response: [ { "imgPaths":[ "gallery/products/55ccb60cddb4d9bded02accb26827ce4" ], "_id":"5f3e961d65c6d591ba04f3d3", "productName":" ...

Adjust the Vue class name dynamically

<div v-bind:class="[updateClassValue? 'chat-item me' : 'chat-item stranger']" v-for="message in msg" :key="message.messageId" > updateClassValue() { for ( const e ...

Error encountered: Attempting to use a class as a function in vue-socket.io is not permitted

I am developing a Vue chrome extension where I am attempting to implement web sockets using vue-socket.io. I have followed the basic instructions on deploying a node server with express and socket.io on Heroku, but I am encountering issues with the conne ...

Nuxt 3 Navigation: dynamic routes showing 404 error

I am currently attempting to create a dynamic link using Nuxt3 ("3.0.0-rc.3") and I am encountering issues with reaching the dynamic slug url. Despite following the instructions on this page, it does not seem to be functioning as expected: https: ...

Vuetify's v-text-field not recognizing custom label slot

After following the instructions in the Vuetify documentation to add a slot for a v-text-field component, as seen here: https://vuetifyjs.com/en/components/text-fields#text-field, I found that the label remained undefined and the slot was ...

Is there a way to automatically refresh a page as soon as it is accessed?

My goal is to create a page refresh effect (similar to pressing Command+R on Mac OS) when navigating to a certain page. For instance: Currently, when I navigate from "abc.com/login" to "abc.com/dashboard" after successfully logging in, the transition occ ...

Issue with tsconfig path alias not resolving when paths are outside of the baseUri

I've encountered an issue in my monorepo where the tsconfig doesn't resolve paths that are located above the current project directory. Here's an overview of my project structure: ── apps │ ├── sahl │ │ ├── index ...

Executing asynchronous methods in a Playwright implementation: A guide on constructor assignment

My current implementation uses a Page Object Model to handle browser specification. However, I encountered an issue where assigning a new context from the browser and then assigning it to the page does not work as expected due to the asynchronous nature of ...

Choosing a particular element within a v-for loop in Vue.js 2

Please review the following code snippet: <div v-for="msg in leftMsg"> div v-if="msg.last_sender" @click.prevent="loadMsg(msg)"> <tr :class="['active',{ 'seens' : !msg.seen, 'selected':msg.isActive}]"> ...