基于vue-tsx的props实体补充插件
这一期给大家分享一个基于vue-tsx的props实体补充插件,可以让我们在使用vue-tsx的时候,可以根据props的类型来补全props的实体。
为什么会开发这个插件
我个人是一个比较喜欢使用vue-tsx来进行开发的,但是在使用vue-tsx的时候,有一个比较痛苦的地方就是,当我们去迁移一些react的组件到vue中的时候,我们需要将react中的props通过手动的方式来实现其对应vue的props实体。这就造成我们的迁移成本会大大的增加。
所以我一直在寻找一个能平衡这个问题的插件,有段时间在翻找仓库的时候发现了一个unplugin-vue-tsx-auto-props的插件,他帮助我们实现了将类型转换成实体的插件。
但是当我使用这个插件的时候发现,这个插件只能引用当前文件中的props的类型,而且不支持继承、合并、交叉类型等等,最重要的是不支持单独定义一个类型文件,然后去引用这个类型文件的props类型。 所以我们在去迁移的时候使用这个插件给我们带来的成本也是很大的。所以我们最后决定基于这个插件进行二次开发,来解决这个问题。这就诞生了我们的vite-plugin-tsx-auto-props的插件。
安装
shell
pnpm add vite-plugin-tsx-auto-props -D
配置
ts
// vite.config.ts
import { defineConfig } from 'vite'
import { tsxAutoProps } from 'vite-plugin-tsx-auto-props'
import vueJsx from '@vitejs/plugin-vue-jsx'
export default defineConfig({
plugins: [
tsxAutoProps(),
vueJsx(),
],
})
使用
你可以像unplugin-vue-tsx-auto-props插件一样使用它提供的功能。
tsx
export interface Props {
foo: string
bar: number
}
export const Single = defineComponent<Props>(() => {
return () => {
return <div></div>
}
})
类型props导入
ts
// typing.ts
export interface Props {
foo: string
bar: number
}
tsx
// index.tsx
import { Props } from './typing'
export const Single = defineComponent<Props>(() => {
return () => {
return <div></div>
}
})
更多的例子
tsx
import { defineComponent } from 'vue'
import type { Props } from './typing'
export interface Props1 {
foo1: string
bar1: number
}
export type Props2 = Props & Props1
export type Props3 = Pick<Props2, 'foo1' | 'foo'>
export const Single = defineComponent<Props>(() => {
return () => {
return <div></div>
}
})
export const Single2 = defineComponent((_props: Props2) => {
return () => {
return <div></div>
}
})
export const Single3 = defineComponent({
setup(_props: Props3) {
return () => {
return <div></div>
}
},
})
这就是我们的插件所实现的功能,当然我们这个插件开发的比较仓库,可能会存在一些小问题,如果大家在使用的过程中发现了问题,可以在issue中提出来,我会尽快的去修复。
如果大家对我们的项目感兴趣,可以给我们的项目一个star,这样可以让更多的人看到我们的项目,也可以让我们的项目变得更好。