搭建vue3-vite-ts空项目模板过程中,收集了几个常见的自定义指令:复制文本、防抖、节流...
由于使用webstorm在使用过程中发现,没有提示信息并提示警告无法识别的 Vue directive
查阅到的配置.dev.d.ts方案,该方案需要配合vscode编辑器以及插件Vue(Official)/Volar才可行
vscode
1. tsconfig.json 或 tsconfig.app.json增加配置
{
...,
"include": ["env.d.ts", "src/**/*", "src/**/*.vue"],
"vueCompilerOptions": {
"plugins": ["@vue/language-plugin-pug"] // 示例:可以挂语言插件,为了自定义指令类型提示增加
}
...,
}
2. 新建directives.d.ts依次配置指令
import type { Directive } from "vue"
import {CopyOptions} from './modules/copy'
import {DebounceOptions} from './modules/debounce'
import {LongPressOptions} from './modules/longpress'
import {ThrottleOptions} from './modules/throttle'
import {WatermarkOptions} from './modules/watermark'
declare module "vue" {
export interface GlobalDirectives {
vCopy: Directive<HTMLElement, CopyOptions>
vDebounce: Directive<HTMLElement, DebounceOptions>
vLongpress: Directive<HTMLElement, LongPressOptions>
vThrottle: Directive<HTMLElement, ThrottleOptions>
vWatermark: Directive<HTMLElement, WatermarkOptions>
}
}
webStorm
webstorm则需要使用web-types.json
web-types.json是 JetBrains 系列 IDE(比如 WebStorm、IntelliJ IDEA) 用来为前端框架/库提供 代码提示、补全和文档支持 的配置文件。
该方式只能提示增加描述,无法校验实际参数类型是否符合
1. 新建web-types.json
{
"$schema": "https://json.schemastore.org/web-types",
"framework": "vue",
"name": "name written in package.json",
"version": "version written in package.json",
"contributions": {
"html": {
"types-syntax": "typescript",
"attributes": [
{
"name": "v-copy",
"description": "复制指令:点击元素即可复制内容到剪贴板。\ninterface CopyOptions {\n text?: string\n successMessage?: string | false\n errorMessage?: string | false\n onSuccess?: (text: string) => void\n onError?: (error: Error) => void\n disabled?: boolean\n messageInstance?: any // 添加 message 实例参数\n}"
},
{
"name": "v-debounce",
"description": "防抖指令:\ninterface DebounceOptions {\n disabled?: boolean\n delay?: number\n immediate?: boolean\n onExecute?: () => void\n onCancel?: () => void\n}"
},
{
"name": "v-longpress",
"description": "长按指令:\ninterface LongPressOptions {\n disabled?: boolean\n duration?: number\n onStart?: (event: Event) => void\n onProgress?: (progress: number, elapsed: number) => void\n onTrigger?: (event: Event) => void\n onCancel?: (event: Event) => void\n}"
},
{
"name": "v-throttle",
"description": "节流指令:\ninterface ThrottleOptions {\n disabled?: boolean\n delay?: number\n leading?: boolean\n trailing?: boolean\n onExecute?: () => void\n onThrottle?: () => void\n}"
},
{
"name": "v-watermark",
"description": "水印指令:\ninterface WatermarkOptions {\n text?: string\n textColor?: string\n font?: string\n fontSize?: number\n textXGap?: number\n textYGap?: number\n rotate?: number\n opacity?: number\n zIndex?: number\n preventDelete?: boolean\n onUpdate?: (el: HTMLElement) => void\n onError?: (error: Error) => void\n}"
}
]
}
}
}
2. package.json中增加
注意引用地址,根据实际修改 ./src/directives/web-types.json
{
...,
"web-types": "./src/directives/web-types.json",
...
}
webstorm只能提示描述信息,无法做到校验ts类型,欢迎大家分享解决方式