简体   繁体   English

导入Typescript文件时找不到Vue模块

[英]Vue modules not found when importing in a Typescript file

I have a Vue project that uses single file class component and typescript loader. 我有一个Vue项目,它使用单个文件类组件和Typescript加载器。 I use VS Code with the Vetur plugin to get very nice code completion inside single file .vue components. 我将VS Code与Vetur插件一起使用,以在单个文件.vue组件中获得非常出色的代码完成率。 This works fine except in my entry.ts file, where I create the root Vue component: 除了在我的entry.ts文件中创建根Vue组件之外,此方法都工作正常:

In entry.ts, I cannot import vue modules! 在entry.ts中,我无法导入vue模块!

index.ts 索引

import Vue from 'vue'                       // this is ok
import App from './components/app.vue'      // vue file not found!
new App({el : '#app'})

ERROR Cannot find module './components/app.vue

app.vue 应用程序

<script lang="ts">
    import Vue from 'vue'                       // this is ok
    import Card from "./card.vue"               // here it works!

    export default class App extends Vue {
    }
</script>

From a .vue file, I can import other .vue modules. .vue文件,我可以导入其他.vue模块。

I have tried leaving out the .vue extension, but that has the same result. 我尝试.vue扩展名,但是结果相同。

I have tried adding the .vue extension to a .d.ts file, but that messes up the Vetur plugin, and reverses the problem (modules only work from .ts files but not from .vue files) 我尝试将.vue扩展名添加到.d.ts文件中,但是这弄乱了Vetur插件,并解决了该问题(模块仅适用于.ts文件,不适用于.vue文件)

Hi Typescript gives you that error because It doesn't know what .vue file is. 嗨,Typescript给您该错误,因为它不知道什么是.vue文件。

But there's a work around for it. 但是有一个解决方法。

In your project directory you can add a file called vue-shims.d.ts 在您的项目目录中,您可以添加一个名为vue-shims.d.ts的文件。

Inside put the following code: 里面放下面的代码:

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

Now typescript will understand .vue files. 现在,打字稿将理解.vue文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM