npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

my-uniapp-tools

v4.2.1

Published

一个功能强大、性能优化的 uni-app 开发工具库,提供剪贴板、本地存储、导航、系统信息等常用功能

Downloads

763

Readme

uni-app 工具库

一个功能强大、经过深度优化的 uni-app 开发工具库,提供剪贴板、本地存储、导航、系统信息、文件上传等常用功能。

✨ 特性

  • 🚀 高性能: 简化缓存机制,删除过度设计,性能提升20%+
  • 🛡️ 类型安全: 完整的 TypeScript 支持
  • 🔧 统一错误处理: 全局错误管理和监控
  • 💾 本地存储: 支持TTL过期管理
  • 🔄 简洁设计: 遵循Linus"好品味"原则,消除特殊情况
  • 📱 跨平台: 支持 H5、App、微信/支付宝小程序

📦 安装

npm install my-uniapp-tools
# 或
yarn add my-uniapp-tools

🚀 快速开始

基础使用

import { copyText, setStorageSync, useToast } from 'my-uniapp-tools';

// 复制文本
await copyText('Hello World!');

// 本地存储
setStorageSync('userInfo', { name: '张三', age: 25 });

// 显示提示
useToast('操作成功');

错误监听(可选)

import { ErrorHandler } from 'my-uniapp-tools';

ErrorHandler.getInstance().onError((error) => {
  console.error(`[${error.module}] ${error.code}: ${error.message}`, error);
});

📚 API 文档

🎯 核心功能

ErrorHandler

全局错误处理器

import { ErrorHandler } from 'my-uniapp-tools';

const errorHandler = ErrorHandler.getInstance();

// 注册错误监听
errorHandler.onError((error) => {
  console.log(`[${error.module}] ${error.message}`);
  // 上报错误到服务器
});

📋 剪贴板功能

copyText(text, config?)

跨平台文本复制

// 基础使用
await copyText('要复制的文本');

// 高级配置
await copyText('要复制的文本', {
  showToast: true,           // 是否显示提示
  successMessage: '复制成功', // 成功提示文本
  failMessage: '复制失败',    // 失败提示文本
	  timeout: 5000             // 超时时间(ms)
	});

💾 本地存储功能

setStorageSync(key, value, options?)

设置本地存储(同步)

// 基础使用
setStorageSync('key', 'value');

// 带过期时间
setStorageSync('userData', userData, {
  ttl: 24 * 60 * 60 * 1000  // 24小时后过期
});

getStorageSync(key, defaultValue?)

获取本地存储(同步)

const userData = getStorageSync('userData', {});

批量操作

// 批量设置
const count = batchSetStorage({
  'key1': 'value1',
  'key2': 'value2'
});

// 批量获取
const data = batchGetStorage(['key1', 'key2']);

cleanExpiredStorage()

清理过期数据

const cleanedCount = cleanExpiredStorage();
console.log(`清理了 ${cleanedCount} 项过期数据`);

🧭 导航功能

navigateTo(options)

页面跳转

const success = await navigateTo({
  url: '/pages/detail/detail',
  params: { id: 123, type: 'product' }
});

useBack(params?, options?)

返回上一页

// 基础使用
await useBack();

// 传递参数给上一页
await useBack({ refreshData: true });

// 高级选项
await useBack(params, {
  delta: 1,              // 返回页面数
  timeout: 5000          // 超时时间
});

safeNavigateTo(options, maxRetries?)

安全导航(带重试机制)

const success = await safeNavigateTo({
  url: '/pages/target/target'
}, 3); // 最多重试3次

📱 系统信息

getPlatform()

获取当前平台

const platform = getPlatform(); // 'weixin' | 'h5' | 'app' | 'alipay' | 'unknown'

useWindowInfo(useCache?)

获取窗口信息

// 使用缓存(默认)
const windowInfo = useWindowInfo();

// 强制刷新
const windowInfo = useWindowInfo(false);

getTopBarMetrics() ⭐ 推荐

获取顶部区域高度的结构化数据

const metrics = getTopBarMetrics();
console.log(metrics.statusBarHeight);      // 状态栏高度
console.log(metrics.navigationBarHeight);  // 导航栏高度(不含状态栏)
console.log(metrics.totalTopHeight);       // 总高度
console.log(metrics.platform);             // 当前平台

getStatusBarHeight()

获取状态栏高度

const height = getStatusBarHeight(); // 返回状态栏高度(px)

getNavigationBarHeight()

获取导航栏高度(不含状态栏)

const height = getNavigationBarHeight(); // 返回导航栏高度(px)

getNavHeight() ⚠️ 已废弃

建议使用: getTopBarMetrics().totalTopHeight

const height = getNavHeight(); // 返回状态栏+导航栏总高度

clearSystemCache()

清除系统信息缓存(横竖屏切换时可调用)

clearSystemCache();

📤 文件上传功能

重要变更: v3.0.0 完全重写了上传模块,旧API已移除

selectAndUpload(options) ⭐ 核心API

选择并上传文件(一体化业务入口)

参数 SelectAndUploadOptions:

  • url (string, 必须): 上传地址
  • type ('image' | 'file' | 'any'): 文件类型,默认 'image'
  • count (number): 最多选择文件数,默认 1
  • maxSelectFileSizeMB (number): 选择阶段体积限制(MB)
  • maxUploadFileSizeMB (number): 上传阶段体积限制(MB)
  • extensions (string[]): 允许的文件扩展名,如 ['jpg', 'png']
  • fieldName (string): 文件字段名,默认 'file'
  • formData (Record<string, any>): 额外的表单数据
  • headers (Record<string, string>): 自定义请求头
  • concurrency (number): 最大并发上传数
  • uploadTimeoutMs (number): 上传超时时间(ms)
  • autoRevokeObjectURL (boolean): H5环境下是否自动回收blob URL
  • beforeUpload (function): 上传前拦截钩子,返回 false 跳过该文件
  • showToast (boolean): 是否显示提示,默认 true
  • successMessage (string): 成功提示文本
  • failMessage (string): 失败提示文本
  • onProgress (function): 进度回调 (file, progress) => void

返回值: Promise<UploadResult[]>

  • file (UniFile | null): 文件信息
  • success (boolean): 是否成功
  • statusCode (number): HTTP状态码
  • data (unknown): 服务器返回数据
  • message (string): 提示信息
// 选择并上传图片
const results = await selectAndUpload({
  url: 'https://api.example.com/upload',
  type: 'image',
  count: 3,
  maxUploadFileSizeMB: 5,
  formData: { userId: '123' },
  headers: { 'Authorization': 'Bearer token' },
  onProgress: (file, progress) => {
    console.log(`${file.name}: ${progress}%`);
  }
});

results.forEach((result) => {
  if (result.success) {
    console.log('上传成功:', result.data);
  } else {
    console.log('上传失败:', result.message);
  }
});

selectAndUploadImage(options)

选择并上传图片的便捷方法(等价于 type: 'image')

const results = await selectAndUploadImage({
  url: 'https://api.example.com/upload',
  count: 1,
  maxUploadFileSizeMB: 5
});

高级用法示例

// 1. 使用并发控制
const results = await selectAndUpload({
  url: 'https://api.example.com/upload',
  count: 10,
  concurrency: 3  // 每次最多同时上传3个文件
});

// 2. 使用上传前拦截
const results = await selectAndUpload({
  url: 'https://api.example.com/upload',
  beforeUpload: async (file) => {
    // 可以在这里做自定义校验
    if (file.size > 10 * 1024 * 1024) {
      console.warn('文件太大:', file.name);
      return false; // 跳过该文件
    }
    return true; // 继续上传
  }
});

// 3. 指定文件扩展名
const results = await selectAndUpload({
  url: 'https://api.example.com/upload',
  type: 'file',
  extensions: ['pdf', 'doc', 'docx'],
  maxSelectFileSizeMB: 20
});

💳 支付(微信公众号 H5)

weChatOfficialAccountPayment(config, onSuccess?, onError?)

在微信内置浏览器中调起支付

import { weChatOfficialAccountPayment } from 'my-uniapp-tools';

// 从服务端获取签名后的支付参数
const payConfig = await fetch('/api/pay/wechat/unified-order', {
  method: 'POST',
  body: JSON.stringify({ orderId: '123456' })
}).then(r => r.json());

const ok = await weChatOfficialAccountPayment(
  payConfig,
  () => uni.showToast({ title: '支付成功', icon: 'success' }),
  () => uni.showToast({ title: '已取消或失败', icon: 'none' })
);

if (!ok) {
  uni.showToast({ title: '请在微信中打开', icon: 'none' });
}

🛠️ 工具函数

deepClone(obj)

深拷贝对象(使用 structuredClone 标准API)

const original = {
  data: [1, 2, 3],
  date: new Date(),
  map: new Map()
};

const cloned = deepClone(original);

deepMerge(target, source)

深度合并对象

const target = { a: 1, b: { c: 2 } };
const source = { b: { d: 3 }, e: 4 };
const merged = deepMerge(target, source);
// 结果: { a: 1, b: { c: 2, d: 3 }, e: 4 }

debounce(func, wait, immediate?)

防抖函数

const debouncedFn = debounce(() => {
  console.log('执行');
}, 1000);

// 取消防抖
debouncedFn.cancel();

throttle(func, wait, options?)

节流函数

const throttledFn = throttle(() => {
  console.log('执行');
}, 1000, {
  leading: true,   // 首次立即执行
  trailing: true   // 结束后执行
});

// 取消节流
throttledFn.cancel();

🎨 使用示例

完整示例

import {
  copyText,
  setStorageSync,
  navigateTo,
  useToast,
  debounce
} from 'my-uniapp-tools';

// 页面中使用
export default {
  data() {
    return {
      userInfo: {}
    };
  },

  onLoad() {
    // 获取用户信息
    this.userInfo = getStorageSync('userInfo', {});
  },

  methods: {
    // 防抖搜索
    onSearch: debounce(function(keyword) {
      // 执行搜索
    }, 500),

    // 复制分享链接
    async onShare() {
      await copyText('https://example.com/share');
    },

    // 跳转详情页
    async goToDetail(id) {
      await navigateTo({
        url: '/pages/detail/detail',
        params: { id }
      });
    }
  }
};

错误处理示例

import { ErrorHandler } from 'my-uniapp-tools';

// 全局错误监听
const errorHandler = ErrorHandler.getInstance();
errorHandler.onError((error) => {
  // 上报错误
  uni.request({
    url: 'https://api.example.com/error-report',
    method: 'POST',
    data: {
      module: error.module,
      code: error.code,
      message: error.message,
      timestamp: error.timestamp
    }
  });
});

📊 性能优化

v3.0.x 优化成果

| 优化项 | 优化前 | 优化后 | 提升 | |------|--------|--------|------| | system模块代码 | 475行 | 385行 | -19% | | 缓存机制 | TTL单例类 | 简单变量 | -96%代码 | | upload模块 | 分散API | 统一入口 | 更易用 | | 深拷贝算法 | 自实现 | structuredClone | 标准化 |

核心优化原则

  • 好品味: 消除特殊情况,而不是重复它
  • 简洁执念: 复杂度是万恶之源
  • 向后兼容: Never break userspace
  • 实用主义: 解决实际问题,不是假想的威胁

🔧 配置选项

存储选项

{
  ttl: number  // 过期时间(毫秒)
}

导航选项

{
  url: string,                    // 页面路径
  params: Record<string, any>,    // 页面参数
  animationType: string,          // 动画类型
  animationDuration: number,      // 动画时长
  events: Record<string, Function> // 页面事件
}

🐛 常见问题

Q: 存储的数据会自动过期吗?

A: 是的,设置了TTL的数据会自动过期,可以调用 cleanExpiredStorage() 手动清理

Q: 支持哪些平台?

A: 支持 uni-app 的所有平台:H5、App、微信小程序、支付宝小程序等

Q: 如何处理导航失败?

A: 使用 safeNavigateTo 函数,它提供重试机制和更好的错误处理

📄 更新日志

v4.0.3 (当前版本)

  • 零配置加载: 彻底移除 initUniAppTools 初始化函数及 PerformanceMonitor 模块
  • 🚀 优化: 系统模块支持运行时平台检测,npm 包引入场景可用
  • 🐛 修复: getPlatform() 在 npm 包环境下的平台识别问题

v3.0.2

  • 新增: getTopBarMetrics() 返回结构化的导航栏高度信息
  • 新增: getNavigationBarHeight() 获取导航栏高度(不含状态栏)
  • 新增: clearSystemCache() 清除系统信息缓存
  • 新增: selectAndUpload() 全新的文件上传统一入口
  • 新增: selectAndUploadImage() 图片上传便捷方法
  • 🚀 优化: system模块删除过度设计的缓存机制,代码减少19%
  • 🚀 优化: 统一导航栏高度API,避免重复计算
  • 🚀 优化: 消除重复的平台判断,提取 isMiniProgram() 辅助函数
  • ⚠️ 破坏性变更: 删除旧的 chooseFile/uploadFile/chooseAndUploadFile 等API
  • ⚠️ 废弃: getNavHeight()getTopNavBarHeight() 标记为废弃,建议使用 getTopBarMetrics()

v2.0.1

  • 🐛 修复已废弃的 uni.getSystemInfoSync API
  • 🚀 本地存储功能大幅增强
  • 🚀 导航模块优化
  • 📝 完善TypeScript类型定义

📜 许可证

MIT License

🤝 贡献

欢迎提交 Issue 和 Pull Request!


注意: 本工具库专为 uni-app 开发优化,在其他环境中可能无法正常工作。