vite-plugin-fetch-dts
v0.7.0
Published
A vite plugin for obtain the vue component type and module type through remote connection
Downloads
74
Maintainers
Readme
vite-plugin-fetch-dts
🚀 一个用于自动获取远程 Vue Components 类型文件的 Vite 插件
功能特性
- ✨ 自动扫描项目中的 Components 远程导入
- 🔄 支持热更新时动态获取类型文件
- 📦 生成 Vue 全局组件类型声明
- 🎯 生成模块类型声明
- 🔧 可配置的日志输出控制
- 🌐 支持 Web Components 事件类型自动转换
- 🔀 支持多种正则表达式匹配模式
安装
npm install vite-plugin-fetch-dts
# 或
pnpm add vite-plugin-fetch-dts
# 或
yarn add vite-plugin-fetch-dts使用方法
在你的 vite.config.ts 中配置插件:
import { defineConfig } from 'vite'
import fetchRemoteDts from 'vite-plugin-fetch-dts'
export default defineConfig({
plugins: [
fetchRemoteDts({
// 扫描文件的 glob 模式,默认为 'src/**/*.vue'
dirs: 'src/**/*.vue',
// 支持多种文件类型:['src/**/*.vue', 'src/**/*.ts', 'src/**/*.js']
// 每次启动时都对dirs进行扫描来获取远程组件类型文件
force: false,
// 组件类型声明文件路径
componentsDts: 'types/remote-components.d.ts',
// 模块类型声明文件路径
modulesDts: 'types/http-modules.d.ts',
// 是否打印详细日志,默认为 false
showLog: false,
// 自定义匹配远程导入 URL 的正则表达式
// 插件会自动解析 import { xxx } from 'url' 和 import('url') 语句
// 然后用这个正则来判断 URL 是否需要处理,默认为 /\/webc\//
// 下面是一些示例:
// 匹配包含 /components/ 的 URL:
// urlRegex: /\/components\//
// 匹配特定域名的 URL:
// urlRegex: /^https:\/\/cdn\.example\.com/
// 匹配多个条件的 URL (包含 webc 或 components):
// urlRegex: /\/(webc|components)\//
// 支持多个正则表达式数组:
// urlRegex: [/\/webc\//, /\/components\//, /^https:\/\/cdn\.example\.com/],
// Web Components 事件转换配置
// 为 true 表示所有引入的 URL 都是 web-component,需要进行事件类型转换
// 为数组表示只对数组中的 URL 进行转换,默认为 false
webcUrl: false,
// 示例:
// webcUrl: true, // 转换所有组件
// webcUrl: ['https://example.com/webc/button.js'] // 只转换指定组件
})
]
})配置选项
| 选项名 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| dirs | string \| string[] | 'src/**/*.vue' | 扫描文件的 glob 模式,支持多种文件类型 |
| force | boolean | false | 是否在启动时强制扫描scanDir获取远程导入 |
| componentsDts | string | 'types/remote-components.d.ts' | 组件类型声明文件路径 |
| modulesDts | string | 'types/http-modules.d.ts' | 模块类型声明文件路径 |
| showLog | boolean | false | 是否打印详细日志信息 |
| urlRegex | RegExp \| RegExp[] | /\/webc\// | 匹配远程导入 URL 的正则表达式,支持单个或数组 |
| webcUrl | boolean \| string[] | false | Web Components URL 配置,用于事件类型转换 |
工作原理
- 扫描阶段:使用 fast-glob 根据 glob 模式扫描项目中的文件(支持
.vue、.ts、.js等) - 解析阶段:提取文件中包含
/webc/路径的 import 语句- Vue 文件:提取
<script>标签中的内容 - JS/TS 文件:直接解析整个文件内容
- Vue 文件:提取
- 获取阶段:并行下载远程类型文件,支持 source map 解析
- 生成阶段:生成 Vue 全局组件声明和模块类型声明文件
- 缓存机制:智能缓存已获取的文件,避免重复下载
示例
基本使用
Vue 文件中使用:
<template>
<div>
<RemoteButton @click="handleClick">点击我</RemoteButton>
</div>
</template>
<script setup>
// 导入远程 Web Component
import { registerWebc } from 'https://example.com/webc/button.js'
RegisterWebc('remote-button')
</script>TypeScript 文件中使用:
// utils/remote-components.ts
import { registerWebc } from 'https://example.com/webc/data-table.js'
RegisterWebc('data-table')扫描多种文件类型
// vite.config.ts
export default defineConfig({
plugins: [
fetchRemoteDts({
// 扫描多种文件类型
dirs: ['src/**/*.vue', 'src/**/*.ts', 'src/**/*.tsx', 'src/**/*.js']
})
]
})许可证
MIT License
