unplugin-vue-components 不能识别组件的自动导入的类型 (pnpm)
阿里云国内75折 回扣 微信号:monov8 |
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6 |
引言
unplugin-vue-components
是一款能帮助组件自动导入的库简单点的说你不需要使用import xx from 'xxx.vue'
这行语句也能实现导入的效果。
<script setup lang="ts">
import ScreenAdpter from '@compontents/ScreenAdpter/index.vue'
import Play from '@components/Play/index.vue'
</script>
<template>
<ScreenAdpter>
<Play></Play>
</ScreenAdpter>
</template>
<style scoped></style>
等同于以下效果
<script setup lang="ts">
</script>
<template>
<ScreenAdpter>
<Play></Play>
</ScreenAdpter>
</template>
<style scoped></style>
效果
这里需要实现的效果如下
发现问题
但是问题来了使用pnpm的用户我相信许多人是实现不了这上效果的😀😀😀。当所有的配置文件配好然后就出现下面的效果啦
问题效果
你会发现在组件使用的地方的类型是any
, 当你去unplugin-vue-components
这里面点击组件是可以进去的那么怎么来解决这个引用问题呢
解决问题
刨根问底
既然组件显示的类型是any
,那么咱们先看下生产的类型声明文件。
// generated by unplugin-vue-components
// We suggest you to commit this file into source control
// Read more: https://github.com/vuejs/core/pull/3399
import '@vue/runtime-core'
export {}
declare module '@vue/runtime-core' {
export interface GlobalComponents {
Play: typeof import('./components/Play/index.vue')['default']
RouterLink: typeof import('vue-router')['RouterLink']
RouterView: typeof import('vue-router')['RouterView']
ScreenAdpter: typeof import('./components/ScreenAdpter/index.vue')['default']
}
}
在自动生成的components.d.ts
文件中的 declare module '@vue/runtime-core'
声明在 pnpm
中只能访问项目的顶级依赖而 @vue/runtime-core
是 vue
模块下的依赖不是顶级依赖导致声明语句失效。yarn
和 npm
的 node_modules
平铺目录结构允许访问所有依赖
解决方案
-
🌟 首选在目录的根目录中创建或编辑
.npmrc
文件并在其中添加以下行public hoist pattern[]=@vue/runtime core
-
不推荐在目录的根目录中创建或编辑
.npmrc文
件并在其中添加以下行shamefully-hoist=true
这样做将使所有嵌套依赖项都可用作顶级依赖项 -
不推荐运行
pnpm add@vue/runtime core -D
将嵌套模块添加为顶级依赖项。您必须确保@vue/runtime
内核的版本与项目中安装的vue
版本相匹配。 -
不推荐使用
0.18.5
版本的unplugin-vue-components
组件而不是最新版本。之所以有效是因为在此版本之前unplugin-vue-components
组件将components.d.ts
中的模块声明为“vue”
。缺点是您将错过插件的最新更新和改进。 -
不建议手动更新
components.d.ts
中的模块声明名称以声明模块“vue”
而不是声明模块“@vue/runtime core”
这很不方便因为每当取消插入vue
组件自动生成新的components.d.ts
文件并覆盖您的更改时您都必须更新模块名称。
注意
如果您选择了选项1或2并创建了.npmrc文件请在之后运行pnpm i
以使用最新的配置更新node_modules
。然后重新加载工作区。自动导入组件的Intellisense
应再次工作。
如果这么操作还是不行就重启下vscode
就ok
啦
祝福
即将接近2022年除夕啦小编在这里祝福大家在新的一年里新年快乐心想事成万事如意代码永无bugger🎉🎉🎉🎉