解决vue3找不到模块或其相应的类型声明

11,098 阅读2分钟

以上截图的报错,最大的关键在于没有相关的声明文件,在ts项目里面,.ts文件是识别不了.vue文件,.vue文件也识别不了.ts文件,这时候就需要.d.ts声明文件来填好这个坑啦。

先来看图一:找不到模块“./App.vue”或其相应的类型声明

网上最容易搜到解决方案就是图一的问题,大体有两个方案:

方案一:

declare module '*.vue' {
  import { defineComponent } from 'vue'
  const Component: ReturnType<typeof defineComponent>
  export default Component
}
复制代码

方案二:

declare module "*.vue" {
  import Vue from "vue";
  export default Vue;
}
复制代码

一顿骚操作下来,只有方案一是适用于vue3+ts+vite2搭配的项目。对于方案二,虽然导入.vue文件的路径不报错,但导入的组件在使用时会报类型声明有问题的错,如图:
image.png问题就在于,方案二导出的Vue,并没有做相关的类型声明,从而匹配不上createApp这个函数声明时定义的参数类型,方案一就做了相关类型声明。
据小道消息:方案二适用于vue2项目,具体是否适用,我并没有去求证。

剩下几张图

'An import path cannot end with a '.ts' extension'

'Cannot find module 'http/api/index' or its corresponding type declarations'

找不到模块“http/jsrsasign.js”或其相应的类型声明

这几个文件都是自定义的.ts/.js文件,所以就需要编写好相关的.d.ts声明文件

declare module 'http/index.ts';
declare module 'router/index.ts';
declare module 'http/api/index.ts';
复制代码

当然你们不想逐个.ts文件声明的话,可以直接来句全局ts的声明,如下:

declare module '*.ts'
复制代码

2、相关声明文件文件引用路径后缀统一:

声明文件中引用的文件是否带后缀,直接关系到在.vue文件引用.ts文件时是否带上后缀的!!!

1、声明不带后缀,引用带后缀:'An import path cannot end with a '.ts' extension'

// shim.d.ts
declare module 'http/index';

// .vue文件
import axios from 'http/index.ts'
复制代码

2、声明带后缀,引用不带后缀:'Cannot find module 'http/api/index' or its corresponding type declarations'

// shim.d.ts
declare module 'http/index.ts';

// .vue文件
import axios from 'http/index'
复制代码