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

@kjts20/tool-taro

v0.1.6

Published

时时工具包 - Taro 多端项目工具

Readme

@kjts20/tool-taro

时时工具包 —— 专为 Taro 多端项目打造的业务工具库
基于 @tarojs/taro 封装,兼容微信小程序、H5、RN 等端。


📦 安装

npm install @kjts20/tool-taro

** peer 依赖 **(请确保项目已安装):

npm install @kjts20/tool @tarojs/taro

提示:@kjts20/tool-taro 的运行依赖 @kjts20/tool 已标记为 external,不会随本包一起打包。业务方如需单独使用 @kjts20/tool 中的工具(如 platformPolyfillunifiedResponseremoveObjectUndefined 等),请直接在项目中引入该包并自行更新版本。


🚀 快速开始

1. 初始化请求

app.ts(或项目入口)中配置接口域名:

import { initHttpServer } from '@kjts20/tool-taro';

initHttpServer('https://api.your-domain.com');

2. 设置路由与 TabBar

import { setRoutes, setTabBar } from '@kjts20/tool-taro';

setRoutes({
    index: 'pages/index/index',
    user: 'pages/user/index',
    order: {
        list: 'pages/order/list',
        detail: 'pages/order/detail'
    }
});

setTabBar({
    list: [
        { pagePath: 'pages/index/index', text: '首页' },
        { pagePath: 'pages/user/index', text: '我的' }
    ]
});

📑 功能模块

一、UI 交互(taro.tools

封装了 Taro 的弹窗、Toast、Loading 等常用交互,统一了回调风格。

import {
    toast, success, error, alert, confirm,
    loading, hideLoading, querySelector
} from '@kjts20/tool-taro';

// Toast
toast('保存成功');
success('提交成功', () => {
    console.log('Toast 结束后执行');
});
error('网络异常');

// 弹窗
await alert('系统维护中,请稍后再试');
const ok = await confirm('确定删除该订单吗?', '删除', '再想想');

// Loading
loading('加载中...');
setTimeout(hideLoading, 2000);

// 查询节点(在页面/组件内使用)
const rects = await querySelector(this, '#header');

二、网络请求(httpServer

基于 @kjts20/toolHttpServer,自动注入 request / uploadFile

import { httpServer, httpServerConfig, initHttpServer } from '@kjts20/tool-taro';

// 初始化
try {
    initHttpServer('https://api.example.com');
} catch (e) {
    console.error('初始化失败', e);
}

// 自定义请求头(例如注入 token)
httpServerConfig.setHeader = function () {
    return { Authorization: `Bearer ${getToken()}` };
};

// 响应拦截
httpServerConfig.responseIntercept = (response) => {
    if (response.code === 401) {
        // 处理登录过期
    }
    return response;
};

// 发起请求
const res = await httpServer.get('/user/info');
const res2 = await httpServer.postJson('/order/create', { skuId: 1001 });

三、本地存储(storage

import { storage } from '@kjts20/tool-taro';

storage.setStorageSync('token', 'xxx');
const token = storage.getStorageSync('token');
storage.removeStorageSync('token');

四、路由导航(navigator

支持页面跳转、返回、刷新,自动识别 tabBar 页面并切换为 switchTab

import { goto, back, refresh, EUseApi, isTabbarPage, getCurrentPage } from '@kjts20/tool-taro';

// 普通跳转
await goto('pages/order/detail', { id: 123 });

// 指定跳转方式
await goto('pages/index/index', {}, { type: EUseApi.reLaunch });

// 返回上一页
await back(1, { refresh: true });

// 刷新当前页
await refresh();

// 获取当前页实例
const page = getCurrentPage();
console.log(page.route, page.options);

五、路由工具(routeTools

针对登录场景的便捷封装。

import { routeTools } from '@kjts20/tool-taro';

// 配置登录页路径
routeTools.setLoginPath('pages/auth/login');

// 判断当前是否是登录页
if (routeTools.isLoginPage()) {
    // ...
}

// 跳转登录页(自动带上当前页路由,方便登录后返回)
routeTools.gotoLoginPage();

// 返回首页
routeTools.toIndex();

六、全局事件(event.tools

基于 @kjts20/toolEvent 实现的全局单例事件总线。

import { getSysEvent, ORG_AUTH_EVENT } from '@kjts20/tool-taro';

const sysEvent = getSysEvent();

// 监听登录状态变化
sysEvent.on(ORG_AUTH_EVENT.LOGIN_STATUS_CHANGE, (isLogin) => {
    console.log('登录状态变化', isLogin);
});

// 触发事件
sysEvent.emit(ORG_AUTH_EVENT.LOGIN_INFO_CHANGE, { nickname: '张三' });

七、组织鉴权(orgAuth

对接后端的用户/员工/客户/商家身份体系,封装了登录、切换身份、Token 检查等逻辑。

import { orgAuth, isLogin, getLoginUser, getLoginUserId } from '@kjts20/tool-taro';

// 小程序授权登录(需先拿到微信登录凭证)
const loginInfo = await orgAuth.mpAuthLogin({ code, encryptedData, iv });

// 检查登录状态
try {
    await orgAuth.mpCheckToken();
} catch {
    // Token 失效,引导重新登录
}

// 是否登录(showTip=true 时会自动弹窗引导)
orgAuth.isLogin(true);

// 获取当前登录用户信息
const user = getLoginUser();
console.log(getLoginUserId());

// 切换身份
orgAuth.changeLoginIdentity('STAFF');

// 退出登录
await orgAuth.logout();

可通过 orgAuth.setApi('mpAuthLogin', '/custom/auth/login') 自定义接口路径。

八、表单校验(validate

import { formValidate } from '@kjts20/tool-taro';

const rules = [
    { key: 'name', required: true, message: '姓名不能为空' },
    { key: 'phone', required: true, regexp: /^1\d{10}$/, message: '手机号格式错误' }
];

formValidate(rules, { name: '张三', phone: '13800138000' })
    .then((data) => {
        console.log('校验通过', data);
    })
    .catch((errDict) => {
        console.log('校验失败字段', errDict);
    });

九、分包/动态加载(subPackage.tools

Taro 环境下使用动态 import() 替代微信小程序原生的 require.async()

import { requirePackage, requirePromise } from '@kjts20/tool-taro';

// 动态引入整个模块
const pkg = await requirePackage('@/subPackages/goods/api');

// 动态引入并调用指定方法
const callApi = requirePromise('@/subPackages/order/api', (mod) => mod.createOrder);
const res = await callApi({ skuId: 1001 });

十、蓝牙工具(ble.utils

封装了蓝牙适配器、设备发现、连接、特征值读取、数据发送、打印机状态查询等完整流程。

import {
    openBluetoothAdapter,
    getBleList,
    connectBle,
    sendData2Ble,
    queryBleStatus
} from '@kjts20/tool-taro';

// 打开蓝牙
await openBluetoothAdapter();

// 搜索设备
const devices = await getBleList((status, msg, detail) => {
    console.log(status, msg, detail);
});

// 连接并获取服务/特征值
const characteristics = await connectBle('xx:xx:xx:xx');

// 发送数据
await sendData2Ble(deviceId, serviceId, characteristicId, [0x1b, 0x33]);

// 查询打印机状态
queryBleStatus(deviceId, (code, msg, detail) => {
    console.log('打印机状态', code, msg);
});

十一、系统信息与工具

import {
    getSystemInfoSync, setSystemInfo, getSystemInfo,
    rpx2px, isIos, checkUpdate, getLoginCode,
    saveImageToPhotosAlbum, restartMiniProgram
} from '@kjts20/tool-taro';

// 系统信息(带 safeArea 兼容处理)
const info = getSystemInfoSync();
setSystemInfo(); // 缓存到 storage

// 单位转换
const px = rpx2px(750); // 屏幕宽度 px

// 版本更新检查(小程序环境有效)
checkUpdate();

// 获取微信登录 code
const code = await getLoginCode();

// 保存图片到相册
await saveImageToPhotosAlbum('https://example.com/pic.png');

// 重启小程序
restartMiniProgram('pages/index/index');

⚠️ 多端适配注意事项

| 功能 | 微信小程序 | H5 | RN | 说明 | |------|----------|----|----|------| | Taro.showModal / showToast / showLoading | ✅ | ✅ | ✅ | 通用 API | | Taro.request / uploadFile | ✅ | ✅ | ✅ | 通用 API | | checkUpdate / restartMiniProgram | ✅ | ⚠️ | ⚠️ | 依赖宿主环境支持 | | saveImageToPhotosAlbum | ✅ | ⚠️ | ⚠️ | H5 需单独处理下载逻辑 | | 蓝牙相关 API | ✅ | ❌ | ❌ | 仅小程序/部分 App 支持 | | getLoginCode / getUserInfo | ✅ | ⚠️ | ⚠️ | 微信生态特有 | | 动态 import() 分包加载 | ✅ | ✅ | ✅ | 需构建工具支持 |

对于非小程序环境,建议在调用端受限 API 前使用 Taro.canIUse 做能力检测,或针对端做条件编译。


🔧 开发说明

构建

npm run build

发布

npm run pub

📄 License

MIT