在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 表示组件的 methodscomputed 类型。
    • 这可以适用于大多数简单的 Vue 组件,但对于更复杂的组件,可能需要更详细的类型定义。
  • export default component;:

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

这段代码的主要作用是:

  • 类型安全:在 TypeScript 项目中,通过声明 Vue 组件模块的类型,使得在导入 Vue 组件时可以获得类型提示和类型检查。
  • 自动推断 :当你在 TypeScript 中使用 .vue 文件时,TypeScript 会自动知道这些文件是 Vue 组件,并应用适当的类型定义。
相关推荐
hongkid6 分钟前
React Native 如何打包正式apk
javascript·react native·react.js
菩提祖师_40 分钟前
量子机器学习在时间序列预测中的应用
开发语言·javascript·爬虫·flutter
未来之窗软件服务1 小时前
幽冥大陆(九十二 )Gitee 自动化打包JS对接IDE —东方仙盟练气期
javascript·gitee·自动化·仙盟创梦ide·东方仙盟
名字越长技术越强1 小时前
html\css\js(一)
javascript·css·html
ヤ鬧鬧o.1 小时前
IDE风格的布局界面
javascript·html5
hxjhnct1 小时前
React 为什么不采用(VUE)绑定数据?
javascript·vue.js·react.js
Knight_AL1 小时前
Vue + Spring Boot 项目添加 /wvp 前缀的完整链路解析(从浏览器到静态资源)
前端·vue.js·spring boot
Hao_Harrision1 小时前
50天50个小项目 (React19 + Tailwindcss V4) ✨| AnimatedCountdown(倒计时组件)
前端·typescript·react·tailwindcss·vite7
谢小飞1 小时前
构建前端监控体系:Sentry私有化部署与项目集成实践
javascript·监控
qq_406176141 小时前
什么是模块化
开发语言·前端·javascript·ajax·html5