Utils 工具函数
@ug666/utils 提供格式化、校验、ID、Storage、类名合并与 API 客户端等常用能力。
导入方式
所有示例均直接使用 @ug666/react 中的真实组件导出。
import { formatBytes, formatDate, generateUUID, isEmail, safeStorage } from '@ug666/utils'变体预览
下面按功能分组展示所有导出能力。
格式化工具
formatBytes / formatDate / formatDateTime / formatRelativeTime / formatNumber / formatDuration
formatBytes(15360) → 15.0 KB
formatDate(new Date()) → 2026年4月18日
formatDateTime(new Date()) → 2026年4月18日 18:14
formatRelativeTime(Date.now() - 3600 * 1000) → 1小时前
formatNumber(1234567) → 1,234,567
formatDuration(125) → 2:05
ID 工具
generateUUID / generatePrefixedId / generateRandomHex
UUID:491fa980-1b2d-4d1d-bd36-1d865bba7c34
Prefixed ID:doc_4b1109557d62
Random Hex:96204977f47dda10
字符串工具
capitalize / truncate / maskEmail / maskPhone
capitalize('astro') → Astro
truncate('这是一个很长的文档标题示例', 10) → 这是一个很长的...
maskEmail('hello@example.com') → h***@example.com
maskPhone('13800138000') → 138****8000
校验工具
isEmail / isPhone / isUrl / isStrongPassword / isEmpty
isEmail('hello@example.com') → true
isPhone('13800138000') → true
isUrl('https://ug666.dev') → true
isStrongPassword('UgDocs2026') → valid
isEmpty() → true
Storage 与 API 客户端
safeStorage / safeSessionStorage / createApiClient / cn
safeStorage.get('docs-demo-theme', 'light') → light
safeSessionStorage.get('docs-demo-tab', 'overview') → overview
createApiClient baseUrl → https://api.example.com
cn(...) → rounded-lg p-4 bg-surface-2
API methods → get, post, patch, delete
状态展示
这些工具既可以在浏览器端用,也适合作为业务逻辑层的基础能力。
尺寸展示
工具函数本身无视觉尺寸概念,展示面积由容器布局控制。
代码示例
可以根据业务模块按需引入需要的工具函数。
import { formatBytes, isEmail, safeStorage } from '@ug666/utils'
const sizeText = formatBytes(1048576)
const valid = isEmail('hello@example.com')
safeStorage.set('theme', 'dark')Props 说明
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| format* | function | — | 字节、日期、时间、数字与时长格式化工具。 |
| generate* | function | — | 生成 UUID、前缀 ID 与随机 Hex。 |
| capitalize / truncate / mask* | function | — | 字符串处理与脱敏工具。 |
| isEmail / isPhone / isUrl / isStrongPassword / isEmpty | function | — | 常见校验工具。 |
| safeStorage / safeSessionStorage | object | — | 安全的浏览器存储封装。 |
| createApiClient | function | — | 创建统一 API 客户端。 |
| cn | function | — | 合并 Tailwind 类名。 |