@catpanel/utils
v1.0.0
Published
Enterprise TypeScript utility library for Vue 3 + Vite + Module Federation projects
Maintainers
Readme
@catpanel/utils
企业级 TypeScript 工具函数库,为 Vue 3 + Vite + Module Federation 项目提供通用工具方法
📦 安装
# 使用 pnpm (推荐)
pnpm add @catpanel/utils
# 使用 npm
npm install @catpanel/utils
# 使用 yarn
yarn add @catpanel/utils🚀 快速开始
TypeScript/ESM
// 导入所需的工具函数
import { isNil, deepClone, formatTime, checkEmail, unique, debounce } from '@catpanel/utils'
// 类型检查
if (isNil(value)) {
console.log('值为 null 或 undefined')
}
// 深拷贝对象
const cloned = deepClone(originalObject)
// 格式化日期
const formatted = formatTime(new Date(), 'yyyy-MM-dd HH:mm:ss')
// 验证邮箱
if (checkEmail('[email protected]')) {
console.log('邮箱格式正确')
}
// 数组去重
const uniqueArray = unique([1, 2, 2, 3, 3]) // [1, 2, 3]
// 防抖函数
const debouncedFn = debounce(() => {
console.log('执行操作')
}, 300)CommonJS
const { isNil, deepClone, formatTime } = require('@catpanel/utils')📚 功能模块
1. 类型检查 (type)
提供完整的类型守卫和类型检查工具。
import { isNil, isEmpty, isObject, isArray, isString } from '@catpanel/utils'
// 类型守卫
isNil(null) // true
isNil(undefined) // true
isEmpty('') // true
isEmpty([]) // true
isObject({}) // true
isArray([1, 2]) // true
isString('hello') // true主要函数:
isNil,isNull,isUndefined- null/undefined 检查isEmpty- 空值检查(支持字符串、数组、对象、Map、Set)isObject,isArray,isFunction- 类型检查isString,isNumber,isBoolean- 基础类型检查isDate,isRegExp,isPromise- 特殊类型检查
2. 数据处理 (data)
提供对象、数组和数据的操作工具。
import { deepClone, camelCase, setSessionStorage, isMobile } from '@catpanel/utils'
// 深拷贝
const obj = deepClone({ a: { b: 1 } })
// 转换下划线为驼峰
camelCase('hello_world') // 'helloWorld'
// Session Storage (带类型安全)
setSessionStorage('user', { name: 'Alice' })
const user = getSessionStorage<{ name: string }>('user')
// 设备检测
if (isMobile()) {
// 移动端逻辑
}主要函数:
deepClone- 深拷贝对象/数组camelCase,underscoreToCamelCase- 命名转换setSessionStorage,getSessionStorage,removeSessionStorage- Session Storage 操作isMobile- 移动设备检测setObjToUrlParams- 对象转 URL 参数removeEmptyValues- 删除空白值swapString- HTML 实体转换
3. 日期时间 (date)
提供日期格式化和时间处理工具。
import { formatTime, getSimplifyTime, getDuration } from '@catpanel/utils'
// 格式化时间
formatTime(new Date(), 'yyyy-MM-dd HH:mm:ss') // '2024-01-15 14:30:45'
// 相对时间
getSimplifyTime(Date.now() - 3600000) // '1小时前'
// 秒转时长
getDuration(3665) // '1小时1分5秒'主要函数:
formatTime- 日期格式化getSimplifyTime- 相对时间显示(刚刚、5分钟前等)addDay- 日期加减getTimeFrame- 获取时间范围getDuration- 秒转天时分秒getMonthDays- 获取月份天数getFirstDayOfMonth- 获取月份第一天getLastDayOfMonth- 获取月份最后一天
4. 验证函数 (check)
提供各种数据格式的验证工具。
import { checkEmail, checkPhone, checkIp, checkPort, checkDomain } from '@catpanel/utils'
// 验证邮箱
checkEmail('[email protected]') // true
// 验证手机号
checkPhone('13812345678') // true
// 验证 IP 地址
checkIp('192.168.1.1') // true
// 验证端口
checkPort(8080) // true
// 验证域名
checkDomain('example.com') // true主要函数:
checkEmail,checkPhone- 邮箱/手机号验证checkIp,checkIp6- IP 地址验证checkPort- 端口验证checkDomain,checkDomainPort- 域名验证checkUrl,checkPanelUrl- URL 验证checkVersion,compareVersion- 版本号比较
5. 表单验证规则 (rule)
Element Plus 表单验证规则(开箱即用)。
import { emailVerify, phoneVerify, pawVerify } from '@catpanel/utils'
// 在 Vue 3 组件中使用
const rules = {
email: emailVerify(),
phone: phoneVerify(),
password: pawVerify({
complex: { length: 8, small: true, big: true, number: true },
message: {
value: '请输入密码',
length: '密码长度至少8位',
small: '密码必须包含小写字母',
big: '密码必须包含大写字母',
number: '密码必须包含数字',
}
})
}主要函数:
defaultVerify- 默认必填规则userVerify- 用户名验证pawVerify- 密码验证(支持复杂度配置)emailVerify,phoneVerify- 邮箱/手机验证ipVerify,urlVerify- IP/URL 验证domainVerify,portVerify- 域名/端口验证
6. 常用工具 (common)
提供日常开发常用的工具函数。
import { getByteUnit, getStyleUnit, clearBlankSpace } from '@catpanel/utils'
// 字节单位转换
getByteUnit(1536) // '1.50 KB'
// 样式单位处理
getStyleUnit(10, 'px') // '10px'
// 清理空格
clearBlankSpace('hello world') // 'helloworld'主要函数:
getByteUnit- 字节单位转换getStyleUnit- 样式单位处理clearBlankSpace- 清理空格isSame- 对象/数组比较getQueryString- 获取URL参数getExtension- 获取文件扩展名getRandomStr- 生成随机字符串
7. 数组工具 (array)
提供丰富的数组操作函数。
import { unique, groupBy, chunk, shuffle, sortBy, flatten, arraySum } from '@catpanel/utils'
// 数组去重
unique([1, 2, 2, 3]) // [1, 2, 3]
// 按字段分组
groupBy([{type: 'a'}, {type: 'b'}], 'type') // { a: [...], b: [...] }
// 分块
chunk([1, 2, 3, 4, 5], 2) // [[1, 2], [3, 4], [5]]
// 打乱
shuffle([1, 2, 3]) // [3, 1, 2] (随机)
// 排序
sortBy([{a: 2}, {a: 1}], 'a') // [{a: 1}, {a: 2}]
// 扁平化
flatten([1, [2, [3]]]) // [1, 2, [3]]
// 求和
arraySum([1, 2, 3, 4, 5]) // 15主要函数:
unique,uniqueBy- 去重groupBy- 分组chunk- 分块shuffle- 打乱sortBy- 排序flatten- 扁平化difference,intersection,union- 集合操作sample- 随机采样arraySum,arrayAvg,arrayMax,arrayMin- 统计paginate- 分页range- 创建范围move,swap- 移动/交换元素
8. 浏览器工具 (browser)
提供浏览器环境检测和操作工具。
import { getOS, getBrowser, copyToClipboard, isMobile } from '@catpanel/utils'
// 获取操作系统
getOS() // 'Windows' | 'Mac' | 'Linux' | 'iOS' | 'Android'
// 获取浏览器类型
getBrowser() // 'Chrome' | 'Firefox' | 'Safari' | 'Edge' | 'IE'
// 复制到剪贴板
await copyToClipboard('text to copy')
// 移动端检测
isMobile() // boolean主要函数:
getOS- 操作系统检测getBrowser- 浏览器检测getDevice- 设备类型检测getBrowserLanguage- 获取浏览器语言isOnline- 网络状态检测isMobile,isIE,isChrome,isFirefox,isSafari- 浏览器判断isWeChat,isQQ- 第三方浏览器判断getUrlParams- URL参数解析copyToClipboard- 剪贴板操作
9. 函数工具 (function)
提供函数式编程工具。
import { debounce, throttle, memoize, retry, compose, pipe } from '@catpanel/utils'
// 防抖
const debouncedFn = debounce(() => console.log('Hello'), 300)
// 节流
const throttledFn = throttle(() => console.log('Hello'), 300)
// 记忆化
const memoizedFn = memoize((n: number) => n * 2)
// 重试
await retry(() => fetchData(), { times: 3, delay: 1000 })
// 函数组合(从右到左)
const composed = compose(
(x: number) => x * 2,
(x: number) => x + 1
)
composed(3) // 8
// 管道(从左到右)
const piped = pipe(
(x: number) => x + 1,
(x: number) => x * 2
)
piped(3) // 8主要函数:
debounce,throttle- 防抖/节流sleep,delay- 延迟执行once- 只执行一次memoize- 记忆化retry- 重试timeout- 超时控制compose,pipe- 函数组合curry- 柯里化settleAll- Promise.allSettled封装limitConcurrency- 并发控制poll- 轮询
10. 数学工具 (math)
提供数学计算和格式化工具。
import { randomInt, clamp, formatNumber, formatCurrency, formatBytes } from '@catpanel/utils'
// 随机整数
randomInt(1, 10) // 1-10之间的随机整数
// 限制范围
clamp(5, 0, 10) // 5
clamp(15, 0, 10) // 10
// 数字格式化
formatNumber(1234567) // '1,234,567'
// 货币格式化
formatCurrency(1234.5) // '¥1,234.50'
// 文件大小格式化
formatBytes(1536) // '1.50 KB'主要函数:
randomInt,randomFloat- 随机数生成clamp- 限制范围formatNumber,formatPercent,formatCurrency- 格式化formatBytes- 文件大小格式化safeMath,add,sub,mul,div- 安全数学运算sum,average,max,min- 统计round,ceil,floor- 四舍五入lerp,mapRange- 插值/映射degToRad,radToDeg- 角度转换isEven,isOdd,isPositive,isNegative- 判断
11. 字符串工具 (string)
提供字符串处理和格式化工具。
import { truncate, maskString, kebabCase, camelCase, snakeCase } from '@catpanel/utils'
// 截断
truncate('Hello World', 8) // 'Hello...'
// 脱敏
maskString('13812345678', 3, 4) // '138****5678'
// 大小写转换
kebabCase('helloWorld') // 'hello-world'
camelCase('hello-world') // 'helloWorld'
snakeCase('helloWorld') // 'hello_world'
// 首字母大写
capitalize('hello') // 'Hello'
// 生成唯一ID
uid('prefix') // 'prefix_1732461234567-abc123'主要函数:
truncate- 截断maskString,maskPhone,maskEmail- 脱敏kebabCase,camelCase,snakeCase- 命名转换capitalize,lowercase- 大小写转换hash- 哈希uid- 唯一IDcompile- 模板编译reverse- 反转countOccurrences- 统计出现次数removeSpaces,removeSpecialChars- 移除字符isJSON- JSON检测toBase64,fromBase64- Base64编解码encodeURL,decodeURL- URL编解码highlightKeyword- 高亮关键词stringToColor- 字符串转颜色
12. 随机数工具 (random)
提供随机数和密码生成工具。
import { getRandomChart, getRandomPwd, getComplexRandomString } from '@catpanel/utils'
// 生成随机字符串
getRandomChart(10, 'default') // 10位随机字符
// 生成密码
getRandomPwd(16) // 16位随机密码
// 生成复杂随机字符串
getComplexRandomString(12) // 包含大小写字母和数字
// 根据配置生成密码
generatePasswordByConfig({
validatePasswordLength: 16,
validatePasswordMixedCaseCount: 2,
validatePasswordNumberCount: 2,
validatePasswordSpecialCharCount: 2
})主要函数:
getRandomChart- 生成随机字符串(支持多种类型)getRandomPrefix- 生成带前缀的随机字符串getRandomPwd- 生成密码getRandom- 生成随机hex字符串getComplexRandomString- 生成复杂随机字符串generatePasswordByConfig- 根据配置生成密码
13. 其他工具 (other)
提供文件类型判断和其他工具。
import { determineFileType, getExtIcon, getFileExt } from '@catpanel/utils'
// 判断文件类型
determineFileType('jpg') // 'images'
determineFileType('jpg', 'images') // true
// 获取文件图标
getExtIcon('image.jpg', 'file') // 'jpg'
// 获取文件扩展名
getFileExt('archive.tar.gz') // 'gz'主要函数:
determineFileType- 文件类型判断getExtIcon- 获取文件图标getFileExt- 获取文件扩展名setColumnCustom- 设置缓存表格列
14. DOM工具 (dom)
提供DOM操作工具。
import { getBody, setCenterInBody, inputFocus, setFullScreen } from '@catpanel/utils'
// 获取body元素
const body = getBody()
// 居中元素
setCenterInBody(element)
// 聚焦元素
inputFocus(element, 'fieldName')
// 全屏
setFullScreen()
exitFullscreen()主要函数:
getBody- 获取body元素setCenterInBody- 居中元素inputFocus,ruleInputFocus- 聚焦setFullScreen,exitFullscreen- 全屏控制clearAssignStyle- 清除样式getElementsByClassName- 按类名获取元素scrollBottom- 滚动到底部getChildElementByClassName- 获取子元素loadFiles- 动态加载文件
15. 错误处理 (error)
提供错误处理和抛出工具。
import { throwConfigError, throwFileTypeError, throwValidationError } from '@catpanel/utils'
// 抛出配置错误
throwConfigError('Invalid config', { key: 'value' })
// 抛出文件类型错误
throwFileTypeError('Invalid file type', { ext: 'xyz' })
// 抛出验证错误
throwValidationError('Validation failed', { field: 'email' })主要函数:
throwConfigError- 配置错误throwFileTypeError- 文件类型错误throwValidationError- 验证错误
16. Worker管理器 (worker-manager)
提供Web Worker管理功能。
import { ProWorkerManager } from '@catpanel/utils'
// 创建Worker管理器
const manager = new ProWorkerManager(workerScript, {
concurrency: 4
})
// 执行任务
const result = await manager.exec(payload, {
priority: 'HIGH',
timeout: 5000,
signal: abortSignal
})
// 终止所有worker
manager.terminate()主要功能:
- 优先级任务调度
- 并发控制
- 超时处理
- 任务取消
- 进度回调
- Worker崩溃自动恢复
🧪 测试
本项目拥有 450+ 测试用例,覆盖 16 个功能模块,确保代码质量和稳定性。
# 运行所有测试
pnpm test
# 查看测试覆盖率
pnpm test:coverage
# 监听模式(开发时使用)
pnpm test:watch
# UI 模式
pnpm test:ui测试文件列表
- ✅
test/array.test.ts- 32 tests - ✅
test/browser.test.ts- 44 tests - ✅
test/check.test.ts- 47 tests - ✅
test/common.test.ts- 11 tests - ✅
test/data.test.ts- 50 tests - ✅
test/date.test.ts- 40 tests - ✅
test/dom.test.ts- 29 tests - ✅
test/error.test.ts- 28 tests - ✅
test/function.test.ts- 29 tests - ✅
test/math.test.ts- 57 tests - ✅
test/other.test.ts- 21 tests - ✅
test/random.test.ts- 34 tests - ✅
test/rule.test.ts- 54 tests - ✅
test/string.test.ts- 57 tests - ✅
test/type.test.ts- 30 tests
🏗️ 构建与开发
# 开发模式(监听文件变化)
pnpm dev
# 构建
pnpm build
# 类型检查
pnpm type-check
# 代码检查
pnpm lint
pnpm lint:fix📊 模块概览
| 模块 | 函数数量 | 测试覆盖 | 说明 | |------|---------|---------|------| | type | 30+ | 30 tests | 类型检查和类型守卫 | | check | 40+ | 47 tests | 数据验证 | | rule | 13 | 54 tests | 表单验证规则 | | data | 17 | 50 tests | 数据处理 | | date | 15 | 40 tests | 日期时间处理 | | common | 10 | 11 tests | 常用工具 | | error | 3 | 28 tests | 错误处理 | | array | 45 | 32 tests | 数组操作 | | browser | 13 | 44 tests | 浏览器检测 | | function | 14 | 29 tests | 函数式编程 | | math | 35 | 57 tests | 数学计算 | | string | 25 | 57 tests | 字符串处理 | | random | 6 | 34 tests | 随机数生成 | | other | 4 | 21 tests | 其他工具 | | dom | 10 | 29 tests | DOM操作 | | worker-manager | 1 class | - | Web Worker管理 |
🔧 TypeScript 支持
本库完全使用 TypeScript 编写,提供完整的类型定义。
// 所有函数都有完整的类型标注
import { isEmpty } from '@catpanel/utils'
const value: string | null = null
if (isEmpty(value)) {
// TypeScript 知道这里 value 是 string | null
// 但 isEmpty 返回 boolean,不会进行类型收窄
}
// 使用类型守卫进行类型收窄
import { isString } from '@catpanel/utils'
if (isString(value)) {
// TypeScript 知道这里 value 是 string
console.log(value.length)
}🤝 贡献指南
欢迎贡献代码!请遵循以下步骤:
- Fork 本仓库
- 创建特性分支 (
git checkout -b feature/AmazingFeature) - 提交更改 (
git commit -m 'Add some AmazingFeature') - 推送到分支 (
git push origin feature/AmazingFeature) - 开启 Pull Request
开发规范
- 遵循 ESLint 规则
- 添加单元测试(新功能覆盖率需 > 80%)
- 更新相关文档
- 确保 TypeScript 类型正确
📄 License
MIT
🙏 致谢
感谢所有为这个项目做出贡献的开发者!
Note: 本库是 panel-docker 项目的一部分,专为 Vue 3 + Vite + Module Federation 微前端架构设计。
