【问题标题】:VueJS/Typescript - Cannot find module './components/Navigation' or its corresponding type declarationsVueJS/Typescript - 找不到模块“./components/Navigation”或其相应的类型声明
【发布时间】:2021-01-20 14:30:59
【问题描述】:

当我将脚本创建为 typescript (lang="ts") 时,我收到一条错误提示

“找不到模块 './components/Navigation' 或其对应的类型声明 (Vetur 2307)。”。

我意识到只有当我将 lang 设置为 ts 时才会发生这种情况,这是我构建 Vue 应用程序所需要的。

app.vue

<template>
  <Navigation />
</template>

<script lang="ts">
import Navigation from './components/Navigation'; // This is where I get the error message

export default {
  name: 'app',
  components: {
    Navigation,
  }
}
</script>

导航.vue

<template>
  <div id="nav">
    <router-link to="/">Home</router-link> 
    <router-link to="/about">About</router-link> 
    <router-link to="/categories">Categories</router-link> 
    <router-link to="/random">Random</router-link>
  </div>
  <router-view />
</template>

<script lang="ts">
export default {
  name: 'Navigation',
}
</script>

【问题讨论】:

    标签: javascript typescript vue.js vuejs2 vuejs3


    【解决方案1】:

    src文件夹中添加文件shims-vue.d.ts,内容如下:

    Vue 2:

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

    Vue 3:

    declare module '*.vue' {
      import type { DefineComponent } from 'vue'
      const component: DefineComponent<{}, {}, any>
      export default component
    }
    
    

    并导入扩展名为 .vue 的组件:

     import Navigation from './components/Navigation.vue';
    

    而不是:

    import Navigation from './components/Navigation';
    

    【讨论】:

    • 根据this github comment: "这是预期的行为......在下一个主要版本中,我们将完全停止支持无扩展名导入单个文件组件(目前只有类型检查错误)。”
    • 谢谢,我刚刚遇到了同样的错误,并且能够使用 shim 文件修复它。我希望官方的 Vue 3 Typescript 文档和指南会告诉你你需要这个。 叹息
    猜你喜欢
    • 2021-04-17
    • 2021-09-21
    • 2021-02-20
    • 2021-10-28
    • 2022-12-16
    • 2022-01-22
    • 2023-01-31
    • 2020-10-19
    相关资源
    最近更新 更多