@core 基础设施
@skyroc/utils
平台无关的通用工具函数,含 ./path 与 ./web 子入口
概览
| 项 | 值 |
|---|---|
| 包名 | @skyroc/utils |
| 版本 | 2.0.2 |
| 依赖 | clsx、colord、crypto-js、dayjs、klona、localforage、nanoid、radash、tailwind-merge |
| 子入口 | .(平台无关)、./path(路径工具)、./web(仅浏览器) |
| 测试 | ✅ 28 个测试文件 |
主入口还 export * from 'radash',即 radash 的全部工具函数都可从 @skyroc/utils 取用。
三个入口的边界
| 入口 | 安全平台 | 内容 |
|---|---|---|
. | Web / RN / Node | 数组、对象、日期、加密、emitter、storage 等纯函数 |
./path | 通用 | 深层路径读写、unflatten、变更路径收集 |
./web | 仅浏览器 | 文件下载、开窗、HTML class、React props 合并 |
Native 端只引用
.,不会误打包浏览器 API。
主入口能力
| 模块 | 关键导出 |
|---|---|
cn | cn(...inputs) — clsx + tailwind-merge 合并类名 |
crypto | Crypto<T> — AES 加解密(.encrypt / .decrypt) |
storage | createStorage<T>(type, prefix)、createLocalforage<T>(driver) |
array | toArray、arraysEqual |
object | shallowEqual、diffObject、isObjectType |
emitter | Emitter — 类型安全事件总线(on/emit/off) |
createSubject | 轻量 Rx Subject |
singleflight | Singleflight / createSingleflight — 合并并发请求 |
priority-queue | PriorityQueue — 泛型优先级队列 |
query | parseQuery / stringifyQuery — URL query 解析 |
reg | 常用正则常量(REG_PHONE、REG_EMAIL、REG_PWD…) |
utils | noop、isNil、isHttpUrl、isMacOs、isPC 等环境/类型守卫 |
date 子模块
提供完整的日期工具(基于 dayjs),分四类:
| 类别 | 函数 |
|---|---|
| 边界 | startOfDay、endOfMonth、getTodayRange、getLastDaysRange… |
| 运算 | addDate、subtractDate、diffDate、fromNow、toTimestamp |
| 比较 | isBefore、isAfter、isToday、isYesterday、isValidDate |
| 格式化 | formatDate、formatDateTime、formatDuration、humanizeDuration |
import { formatDate, getTodayRange, isToday } from '@skyroc/utils';
formatDate(Date.now()); // '2026-06-02'
const [start, end] = getTodayRange();
isToday('2026-06-02'); // true./path 子入口
围绕「对象深层路径」的读写与变更追踪:
import { deepGet, deepSet, unflatten, collectChangedLeafPaths } from '@skyroc/utils/path';
deepGet(obj, 'user.address.city');
deepSet(obj, ['list', 0, 'name'], 'Alice');
unflatten({ 'a.b': 1, 'a.c': 2 }); // { a: { b: 1, c: 2 } }这套工具是 @skyroc/form 字段管理的底层支撑。
./web 子入口
import { downloadFileFromUrl, openWindow, toggleHtmlClass, mergeProps } from '@skyroc/utils/web';
downloadFileFromUrl('/export.xlsx', 'report.xlsx');
openWindow('https://example.com', { target: '_blank' });
toggleHtmlClass('dark', true);| 函数 | 用途 |
|---|---|
downloadFileFrom* | 从 url / base64 / blob 触发下载 |
openWindow | 安全地打开新窗口 |
toggleHtmlClass | 切换 <html> 上的 class(暗色模式等) |
mergeProps / withClassName | React props 合并 |
getEventValue、isCheckBoxInput… | 表单 input 工具 |
常用示例
import { Crypto, createStorage, Emitter } from '@skyroc/utils';
// 类型安全的本地存储
const storage = createStorage<{ token: string }>('local', 'app:');
storage.set('token', 'xxx');
// 加密
const crypto = new Crypto<{ id: number }>('secret-key');
const enc = crypto.encrypt({ id: 1 });
const dec = crypto.decrypt(enc); // { id: 1 } | null
// 事件总线
const emitter = new Emitter<{ login: string }>();
emitter.on('login', name => console.log(name));
emitter.emit('login', 'admin');