在Vite+TypeScript项目中导入组件时会报找不到模块的声明文件

在使用Vite创建Vue3项目时,遇到找不到模块"@/components/***.vue"的错误。解决方法包括在src下的vite-env.d.ts文件中添加特定代码,或者如果文件不存在,则在根目录创建env.d.ts或者vite-env.d.ts文件并追加相应代码,从而完美解决此类模块导入问题。

TypeScript 复制代码
/// <reference types="vite/client" />

declare module "*.vue" {
	import type { DefineComponent } from "vue";
	// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/ban-types
	const component: DefineComponent<{}, {}, any>;
	export default component;
}
  • declare module "*.vue":

    • 这表示 TypeScript 将处理所有以 .vue 结尾的文件。
    • 这种声明告诉 TypeScript 如何处理 Vue 组件文件,确保这些文件在导入时具有适当的类型信息。
  • import type { DefineComponent } from "vue";:

    • 从 vue 包中导入 DefineComponent 类型。这是 Vue 3 的一个类型,用于定义 Vue 组件的类型。
  • const component: DefineComponent<{}, {}, any>;:

    • 声明一个名为 component 的常量,它是一个 DefineComponent 类型。
    • DefineComponent<{}, {}, any> 表示组件的类型:
      • 第一个 {} 表示组件的 props 类型。
      • 第二个 {} 表示组件的 data 类型。
      • any 表示组件的 methods 和 computed 类型。
    • 这可以适用于大多数简单的 Vue 组件,但对于更复杂的组件,可能需要更详细的类型定义。
  • export default component;:

    • 导出 component 作为默认导出。这使得 TypeScript 知道你可以从 Vue 组件文件中默认导出一个组件。

这段代码的主要作用是:

  • 类型安全:在 TypeScript 项目中,通过声明 Vue 组件模块的类型,使得在导入 Vue 组件时可以获得类型提示和类型检查。
  • 自动推断 :当你在 TypeScript 中使用 .vue 文件时,TypeScript 会自动知道这些文件是 Vue 组件,并应用适当的类型定义。
相关推荐
一 乐1 天前
动漫书销售商城|基于springboot + vue动漫书销售商城(源码+数据库+文档)
java·数据库·vue.js·spring boot·毕业设计
tiankongdeyige1 天前
游戏战斗系统学习第2篇:有限状态机 (FSM)
学习·游戏·typescript
admin and root1 天前
「AI安全篇」实战AntiDebug自动化JS逆向加解密MCP
javascript·人工智能·网络安全·自动化·漏洞挖掘·cnvd·src赏金
wengad1 天前
从 wangEditor 迁到 wangEditor-next
前端·javascript·vue.js
行者-全栈开发1 天前
【前端/JS框架】CVE-2026-3854:GitHub Enterprise Server X-Stat注入XSS漏洞深度剖析与紧急修复指南
前端·javascript·github
怕浪猫1 天前
2026年金九银十,我面了22个前端
前端·javascript·面试
FYKJ_20101 天前
django电影推荐系统55066-计算机课程设计、毕业设计
vue.js·spring boot·python·mysql·typescript·spark·django
前端的日常1 天前
一个人+AI做情侣食谱小程序,30天纯赚
前端·javascript·后端
qq_316837751 天前
阿里云百炼 fun-asr-realtime uniapp vue3 调用
javascript·vue.js·uni-app
李剑一1 天前
AntDesign老版本没有月份和年份区间选择组件?我封装了一个完美版,附源码!
前端·vue.js