Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove .vue extension from imports when using TypeScript in Vue.JS?

I created a project with vue-cli3 and included TypeScript

My src/app.vue:

<template>
  <div id="app">
    <hello-world msg="test"/>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import HelloWorld from '@/components/HelloWorld';

@Component({
  components: { HelloWorld },
})
export default class App extends Vue {}
</script>

the compiler throwing an error in "Cannot find module '@/components/HelloWorld'";

The component HelloWorld exists.

However, if I remove the lang="ts" or add the .vue extension then everything compiles fine. In my tsconfig.json, i have

  "paths": {
    "@/*": [ "src/*" ]
  },

Is it an issue with tsconfig.json or something else?

like image 975
Andre12 Avatar asked Oct 18 '18 18:10

Andre12


People also ask

Does vue2 support TypeScript?

You should also be familiar with Vue, vue-loader, and webpack. Vue 2 already has good support for TypeScript, and the recently published Vue 2.7 backported a lot of useful features from Vue 3, like composition API, <script setup> , and defineComponent , further improving the developer experience of TypeScript in Vue.

Can we use TypeScript in Vue?

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.

What is .Vue extension?

VUE file extension is mainly associated with single file components used by Vue, an open-source, frontend JavaScript framework for building user interfaces. Such VUE single-file components are modules containing source code (typically for a single UI component) which can be exported or reused in a Vue application.


1 Answers

In your sources root folder you probably have a file named shims-vue.d.ts with contents like these:

declare module '*.vue' {
  import Vue from 'vue'
  export default Vue
}

What this file does is tell the Typescript compiler that all files ending in .vue have the Vue type. Otherwise, those files have no type and Typescript cannot work with them.

This is why you need the .vue extension: if you remove it, Typescript doesn't know the type of the file and can't compile. So, in short, the answer is that you can't remove the extension.

More advanced answer:

Theoretically, you can remove the extension, but you would need to declare the module shim with a different expression. For example, you could tell Typescript that all the files in a folder have the Vue type. This is, however, way worse than just shimming the .vue extension, which is the recommended default.

like image 102
Varo Avatar answered Sep 21 '22 05:09

Varo