vue3&typescript,shims-vue.d.ts中declare module的vue声明

webpack已经有了vue-loader这些loader了,为什么还需要declare module '*.vue'呢?

declare module 是为了告诉 tsc 这是一个"模块"。

如果不声明, IDE 里因为 tsc 类型检查, lint 会标红。

但vue-loader 是在 Webpack 构建阶段使用。IDE 做智能补全提示、还有 lint 时又不用到它vue-loader。

之所以搞这么复杂,就是因为 tsc 只能识别 .js、.ts、.mjs、.json 等几种后缀的文件类型,并不"认识" .vue 文件。

所以后来为了更好地支持 TypeScript 类型推断,Vue3 中专门搞了一个 vue-tsc,用来取代默认的 tsc,就不需要你手动写一堆 declare module 了。

举例1

bash 复制代码
declare module '*.vue' {
  import { DefineComponent } from 'vue'
  const component: DefineComponent<{}, {}, any>
  export default component
}

举例2

bash 复制代码
// my-js-module.js
function greet(name) {
  return 'Hello, ' + name;
}

module.exports = {
  greet,
};

然后你在 TypeScript 项目中引入这个模块:

bash 复制代码
// main.ts
import { greet } from 'my-js-module';

为了让 TypeScript 编译器能正确理解 my-js-module 模块的类型信息,你需要创建一个名为 my-js-module.d.ts 的类型声明文件

bash 复制代码
// my-js-module.d.ts
declare module 'my-js-module' {
  export function greet(name: string): string;
}
相关推荐
️公子2 小时前
可插拔 13 款实时棋牌对战平台实践:房间容器、Plugin SDK 与幂等账本
websocket·typescript·游戏开发·monorepo·插件架构·棋牌平台·实时对战
FungLeo3 小时前
成为全栈·Vue 管理后台篇·Vue3 + Vite + Naive UI:后台工程基座怎么搭
前端·vue.js·ui·typescript·vite·前端工程化·biome
FungLeo3 小时前
成为全栈·Vue管理后台篇·<scriptsetup>:把页面拆成可读、可测的 Vue 组件
前端·javascript·vue.js·typescript·前端组件化·composition api·vue sfc
软件技术NINI1 天前
基于SpringBoot和Vue的新能源汽车销售推荐系统
java·vue.js·spring boot·后端·汽车·毕业设计·毕设
招风的黑耳1 天前
SpringBoot+Vue+MySQL 民宿在线预定平台 完整可运行版(源码+文档)
vue.js·spring boot·mysql
10share2 天前
基于大模型的 i18n 方案:把中文原文当 Key,轻松搞定多语言维护
前端·vue.js
啾咪orJIUMI2 天前
Vue 3 + 高德地图封装实战:点位、区域、Loca 流光与 Vue 信息窗体
前端·vue.js
FRing032 天前
vue2干货总结8(路由模块封装、router-link、声明式导航、路由重定向、编程式导航)
开发语言·前端·vue.js·vue2
无懈可击2 天前
Vue 可视化AI表单设计器 FcDesigner v3.6 版本发布,支持导出 SQL功能!
vue.js·开源·ai编程
徐小夕2 天前
JitArchives,一款基于JitWord协同AI文档打造的企业级电子档案系统
前端·vue.js·github