0.1.9 • Published 1 year ago

@tylerchao/miniprogram-tools v0.1.9

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

小程序通用函数库miniprogram-tools

文件结构

  • config.js ⇒ 几个基本配置
  • utils.js ⇒ 与小程序不相关的基础函数
  • weapp.js ⇒ 与小程序相关的应用级工具函数
  • index.js ⇒ 整合前面的文件统一输出所有api

安装与使用

npm install @tylerchao/miniprogram-tools
import {
  compareVersions,
  mp,
  alert,
  confirm,
  toast,
  getSystemInfo,
  linkTo,
  storage,
} from '@tylerchao/miniprogram-tools';

// or
import { isEmpty, isPlainObject } from '@tylerchao/miniprogram-tools/utils';
import { mp, storage } from '@tylerchao/miniprogram-tools/weapp';

API

Config:

PREFIX: storage存储键需要的前缀,除非小程序不支持getAccountInfoSync(基础库v2.2.2以下),否则不需要自定义,如有特殊需求,按以下方式更新:

storage.updatePrefix(PREFIX: String);

WX_APIS: 配置需要Promise化的以wx开头的小程序api,这里只配置了showToast/showModal/request三个wx api,其它的需要在用到的地方先执行:

mp.add(apiList: Array);

Utils

isPlainObject(input: any): 判断是否为键值对形式的纯对象

isPlainObject({}) // true
isPlainObject({ a: 1, b: 2, c: x => x * x }) // true
isPlainObject(true) // false
isPlainObject(null) // false
isPlainObject('plain') // false

isEmptyObject(input: any): 判断是否为"空纯对象"

isEmptyObject({}) // true
isEmptyObject(null) // false
isEmptyObject({ a: 1 }) // false
isEmptyObject(false) // false
isEmptyObject('') // false

isEmptyArray(input: any): 判断是否为"空数组"

isEmptyArray([]) // true
isEmptyArray(['']) // false
isEmptyArray(false) // false
isEmptyArray('') // false
isEmptyArray({}) // false

isEmpty(input: any, inclusions?: Array, exclusions?: Array): 判断是否为空值

默认定义'', null, undefined, 'undefined',[], {} 几种为空值的情况。

  • inclusions: 其它做为空值的情况
  • exclusions: 排除以上无需判断为空值的情况
isEmpty('') // true
isEmpty(undefined) // true
isEmpty('undefined') // true
isEmpty(false) // false
isEmpty([]) // true
isEmpty({}) // true
isEmpty(false, [false]) // true
isEmpty(null, [], [null]) // false

getKeys(input: Object | Array): 过滤出对象或数组中有值的键并返回包含这些键的数组

getKeys({ a: 1, b: '', c: null, d: false }) // ['a', 'd']
getKeys({ a: { a: null, b: {} }, b: '', c: null, d: false, e: [null, undefined] }) // ['d']

removeEmptyValues(input: Object | Array): 删除对象或数组中属性值为空值、空数组、空对象的键

removeEmptyValues({ a: 1, b: '', c: null, d: false }) // {a: 1, d: false}
removeEmptyValues([0, 1, '', { c: 1, d: null }, { e: '' }]) // [0, 1, { c: 1 }]

clone(input: Object | Array, keys?: Array | Function): 实现深拷贝json数据的最简单版本,可以选择只拷贝某些键值

  • keys: 如果该参数是一个数组,则只有包含在这个数组中的属性名才会被克隆;如果该参数是一个函数,则在克隆过程中,被克隆的值的每个属性都会经过该函数的转换和处理;属性值为undefined以及函数的属性名不会被克隆
clone({ a: 1, b: '', c: null, d: false, e: undefined }) // {a: 1, b: "", c: null, d: false}
clone({ a: 1, b: '', c: null, d: false }, ['a', 'b', 'c']) // {a: 1, b: "", c: null}

capitalize(input: String, prefix?: String): 首字母大写

  • prefix: 前缀,放在首字母前面
capitalize('prefix suffix') // Prefix suffix
capitalize('prefix', 'suffix') // suffixPrefix

toQueryString(input: Object, encode?: Boolean, sort?: Boolean): 转换纯对象为url查询字符串

  • encode: 是否对属性值进行URL编码
  • sort: 是否对属性名进行排序
toQueryString({ c: 1, b: '', d: null, a: false, f: undefined }) // c=1&a=false
toQueryString({ c: 1, b: '', d: null, a: false, f: '中文' }, true) // c=1&a=false&f=%E4%B8%AD%E6%96%87
toQueryString({ c: 1, b: '', d: null, a: false, f: undefined }, false, true) // a=false&c=1

generateSignature(input: Object, { encrypt: Function, isSorted?: Boolean, appKey?: String, token?: String, secret?: String }): 生成签名算法

  • encrypt: 加密函数,一般需自行引入sha256
  • isSorted: 是否需要对 input 排序
  • appKey: 公共参数,应用的appKey
  • token: 公共参数,用户身份凭证
  • secret: 要添加到最后的secret字符串
import sha256 from 'js-sha256';

generateSignature({c: 1, b: '', d: null, a: false, f: undefined }, { encrypt: sha256 });

generateSignature({ c: 1, b: '', d: null, a: false, f: '中文' }, {
  encrypt: sha256,
  isSorted: false,
  appKey: 'xwrlt456',
  secret: 'xxxxx',
});

compareVersions(v1: String, op: String, v2: String): 比较两个版本号大小,经常用于比较是否低于某个版本的基础库。

  • v1/v2: 要比较的版本号
  • op: 比较运算符,可用的有>,<,=,>=,<=
compareVersions('2.5.0', '=', '2.4.9') === false
compareVersions('v2.10.1', '>', 'v2.9.1') === true
compareVersions('v2.10.1-alpha.2', '>', '2.10.1-alpha.1') === true
compareVersions('v2.10.1-alpha.2', '>', '2.10.1-beta.1') === true
compareVersions('v2.10.1-alpha.2', '>=', '2.10.1-beta.1') === true

sleep: 等待n毫秒

(async () => {
  console.log('a');
  await sleep(5000);
  console.log('b');
})();

Weapp

promisify: 任何类似wx开头的api,以successfail作为回调的函数,都可以用此方式Promise化。

const request = promisify(wx.request);

request({ data }).then(res => {
  // ...
}).catch(console.error);

const res = await request({ data }).catch(e => e);
console.log(res);

mp: 小程序wx对象经Promise化后的对象,项目中使用到的以wx开头的api需要在使用到的地方调用mp.addApis方法先定义,也可以统一在一个地方定义,请按需配置 注:小程序基础库2.10.2以上部分异步api支持promise调用方式,此时返回原生的promise。

mp.apiList: 查询已被mp对象Promise化过的wx api,可以知道有哪些API已被定义;

console.log(mp.apiList);

mp.add(apiList: Array): 按需添加需要Promise化的wx api,或在app.js中统一添加小程序中用到的wx api。

mp.add(['login', 'getLocation']);

mp.login().then(res => {
  ...
});
mp.request({ data })
  .then(res => {
    ...
  })
  .catch(console.error);

const res = await mp.request({ data }).catch(e => e);
console.log(res);

getPage(previous?: Number): 获取当前页面栈中的页面

  • previous: 相对于当前页面的索引,负数
getPage()
getPage(-1)

storage(key?: String, value?: Any, expire?: Number): 小程序本地存储

storage('key') // 读取key存储的数据
storage('key', null, true) // 读取数据的有效期
storage('key', 'value') // 存储数据
storage('key', null) // 删除数据
storage('key', 'value', -1) // 删除数据
storage('key', 'value', 3600) // 存储数据,有效期为1个小时

storage.updatePrefix(prefix: String): 改变storage存储键的前缀,默认为小程序的appid和当前环境,一般无需改变。

storage.updatePrefix(appid + env);

alert(content: String, options?: Object): 警告对话框(对模态对话框的进一步封装,并Promise化)

  • options: 同showModal的选项
alert('警告:');
await alert('警告:');

alert('请开启授权', {
  title: '提醒',
  success: wx.openSetting,
});

confirm(content: String, options?: Object): 确认对话框(对模态对话框的进一步封装,并Promise化)

  • options: 同showModal的选项
confirm('警告:');
const res = await confirm('警告:');
if (res.confirm) {
  ...
}

confirm('请打开设置页开启授权', {
  confirmText: '打开',
  success(res) {
    if (res.confirm) wx.openSetting();
  },
});

block(content: String, options?: Object): 带返回的对话框(对模态对话框的进一步封装,并Promise化)

点击返回之后,直接返回到上一页。

  • options: 同showModal的选项
block('此商品已下架。');

toast(title: String, icon?: String): 消息提示框(对showToast的进一步封装,并Promise化)

  • icon: 小程序内置的几种图标
toast('加载失败,请重试');
toast('加载成功', 'success');

formatPath(path: String): 转换页面路径为标准路径/pages/index/index形式

  • path: 默认页面要放在pages目录,这时只需写页面文件名,请看示例:
formatPath('index'); // 默认不需要带路径,会转成/pages/index/index
formatPath('cart/index'); // => /pages/cart/index
formatPath('pages/fail/fail'); // => /pages/fail/fail
formatPath('pages/fail'); // => /pages/fail/fail
formatPath('/common/fail/fail'); // 如不在pages文件夹请写绝对路径 => /common/fail/fail
formatPath('index?a=1'); // => /pages/index/index?a=1
formatPath('coupon'); // => /pages/coupon/coupon

linkTo(path: String, query?: Object | String, openType?: String): 跳转页面

  • path: 默认为页面放在pages目录,并且页面文件夹与页面同名,这时只需写文件名,否则请写绝对路径。
  • query: 如果传入Object则会处理为url查询字符串,如果传入String则作用同jumpType
  • openType: 跳转方式,支持navigate/navigateTo,redirect/redirectTo,swithTab,reLaunch,默认为navigateTo跳转方式。
  • 注:如果页面栈中的页面超过10个,会自动转为redirectTo跳转方式。
linkTo('index'); // 默认不需要带路径,会转成/pages/index/index
linkTo('index', 'redirect'); // 同上
linkTo('cart/index'); // => /pages/cart/index
linkTo('pages/fail/fail'); // => /pages/fail/fail
linkTo('pages/fail'); // => /pages/fail/fail
linkTo('/common/fail/fail'); // 如不在pages文件夹请写绝对路径
linkTo('index?a=1'); // 可直接带路径参数
linkTo('coupon', {
  id: 1,
  type,
}, 'reLaunch');

getSystemInfo: 获取所有系统参数(同wx.getSystemInfoSync),并加入几个有用的字段,如下:

  • titleBarHeight: 标题栏高度
  • systemName: 当前系统的名字,全小写
  • pxRatio: 根据屏幕宽度计算得到的px比率
0.1.9

1 year ago

0.1.7

3 years ago

0.1.6

4 years ago

0.1.5

4 years ago

0.1.4

4 years ago

0.1.3

4 years ago

0.1.2

4 years ago

0.1.2-0

4 years ago

0.1.0

4 years ago