Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to work with Typescript in .vue files using VS Code?

Tags:

I'm using Visual Studio Code, Vue 2 (webpack template) and Typescript.

This is 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 working fine, but I would like to have intellisense inside <script lang="ts"> tag as it happens in .ts files, so how can I achieve that?

Question 2: In my main.ts I have import App from './App', but "./App" is underlined in red since VS Code can't find the .ts file. Is there a way to make the editor recognizes .vue before compile time (in editing time)?

Update (2018-03-25): I highly recommend everyone who wants to setup typescript to read this

like image 595
Oswaldo Avatar asked Feb 05 '17 23:02

Oswaldo


People also ask

How do I create a TypeScript project in Vscode?

Configuration. Create an empty folder, open Visual Studio Code and move to that folder. Now we want to setup a convenient build process in order to run the project with a couple of buttons. Press Ctrl+Shift+P and type Configure Task Runner, press Enter to select it then TypeScript - tsconfig.

Can we use TypeScript in Vuejs?

Vue is written in TypeScript itself and provides first-class TypeScript support. All official Vue packages come with bundled type declarations that should work out-of-the-box.


1 Answers

For Q1, put the Typescript code into a separate script.ts file and include it in App.vue like:

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

For Q2, as suggested by @Oswaldo, you can defined a vue.d.ts file that has the following content:

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

If you put this file in the ${Project_ROOT}/typings folder, you need to include this type file in your tsconfig.json like

"typeRoots": ["./typings"] 

Then you can import *.vue file with the .vue postfix:

import App from './App.vue' 

If you don't like to include the .vue postfix, you can put all Vue components in a single folder such as src/components and change the vue.d.ts as the following:

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

The src is defined webpack.base.conf.js as an alias for an absolute path.

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

Then you need to use the full path to import a component without the .vue postfix:

import App from 'src/components/App' 

Both are not elegant solutions but the red underline is gone.

like image 144
Ying Avatar answered Sep 28 '22 03:09

Ying