unplugin-vue-components自动导入的组件类型失效问题

unplugin-vue-components0.25.1版本中恢复了从vue而不是@vue/runtime-core中导出类型。Volar中目前也是这么推荐的。但是我遇到了这个issue中的问题。也就是当同时使用unplugin-auto-importunplugin-vue-components时,并且unplugin-auto-importvueTemplate设置为true,并且tsconfigcomponents.d.ts排在auto-imports.d.ts后面时会识别不到GlobalComponents类型。解决方法如issue中提到的,将auto-imports.d.ts放在tsconfiginclude的最后一项即可。

目前仍然困扰的是vue-router中仍然在通过@vue/runtime-core导出类型。不过Vue的这个PR已经有了进展,或许3.4.0会修复这个相关问题?


原文 2023-05-06

VSCode中我们使用Volar作为Vue3的extension,这是前提。

我们都知道,ts中重复声明的interface会合并,可以实现接口的扩展。Volar就是基于重复声明GlobalComponents接口实现全局组件类型提示的。 当使用Vue3时,unplugin-vue-components自动生成的类型文件长这样:

import '@vue/runtime-core'
export {}
declare module '@vue/runtime-core' {
export interface GlobalComponents {
// global components
}
}

vue/language-tools(volar)源码中我们可以看到,Volar是从vue @vue/runtime-core @vue/runtime-dom模块中导入GlobalComponents类型的。同时从Volar的README中我们也看到,Volar推荐在Vue3中从@vue/runtime-core模块中声明导出GlobalComponents。这一点是因为README中提到的一个vue的PR:https://github.com/vuejs/vue-next/pull/3399 。从这个PR的这一行中我们可以看到,GlobalComponents是从runtime-core/src/component.ts导出的,这也是为什么Volar要我们从@vue/runtime-core中导出GlobalComponents接口。但是这个PR到目前为止都没有被合并,所以算是Volar为未来做的一个铺垫。

因此,回到我们的unplugin-vue-components导入的组件没有类型提示上, 我们可以从vue的package.json中看到,vue的dependencies里目前并没有@vue/runtime-core。如果你使用的是pnpm,pnpm为了避免幽灵依赖,默认是不会依赖提升的,这也就导致了unplugin-vue-components声明的类型文件中的import '@vue/runtime-core'无效。因此我们解决方法有两种:

  1. 提升依赖

可以通过在.npmrc中声明public-hoist-pattern或者shamefully-hoist提升依赖:

public-hoist-pattern[]=*@vue/runtime-core* # 或者 shamefully-hoist=true
  1. 直接安装@vue/runtime-core
pnpm add -D @vue/runtime-core

@vue/runtime-core添加到项目的devDependencies,上面的导入就生效了。

评论加载中 (ง •̀ω•́)ง