并分享项目中使用到的库
一、使用三方库时注意事项
1. 版本兼容问题
在使用 ohpm install 库名 命令安装三方库时,可能会遇到版本不匹配的问题。尽管代码在IDE中没有提示错误,但在运行时可能会抛出异常。此时需要前往OpenHarmony三方库中心仓库查看最新的版本号,并尝试更换不同的版本。
2. 自动化测试配置问题
在配置自动化测试时,可能会遇到因版本号使用 ^ 导致的问题。例如,在 oh-package.json5 文件中,应该将 @xxx": "^1.0.0" 更改为 @xxx": "1.0.0",以确保版本号精确指定。
3. ohpm命令识别问题
如果在使用 ohpm install 命令时遇到 “The term 'ohpm' is not recognized as the name of a cmdlet” 错误,说明DevEco Studio的环境变量配置不正确或版本过旧。建议卸载旧版本并重新安装最新版DevEco Studio。
4. 跨平台库移植问题
Android或iOS中使用的.so库无法直接移植到HarmonyOS项目中使用。需要采用HarmonyOS支持的方式来编写C++代码,并重新编译生成.so库。
二、主要使用的三方库
1、数据解析方案
接口返回的数据通常需要转换为类(class)的形式来方便使用。这样不仅提高了代码的可读性和可维护性,还可以利用类的方法来进行数据处理。
推荐库:
• class-transformer
• @yunkss/ef_json
• @pura/harmony-utils
其中,class-transformer 和 @pura/harmony-utils 在解析数据时,可以保留类中的方法。在我们的项目中选择了 class-transformer。
代码示例:
输出:
2、网络请求方案
网络请求是移动应用中常见的功能之一,HarmonyOS提供了多种库供选择。
推荐库:
• @ohos/axios
• @yunkss/ef_axios
• import { http } from '@kit.NetworkKit';(官方)
由于团队习惯使用Axios,因此选择了 @ohos/axios。
3、加密方案
加密是保护数据安全的重要手段,HarmonyOS提供了多种库供选择。
推荐库:
• import { cryptoFramework } from '@kit.CryptoArchitectureKit';(官方)
• ohpm install @yunkss/ef_crypto
• class-transformer
在项目中广泛使用了 class-transformer,因为它除了数据解析外还有其他实用功能。
4、设备唯一标识
获取设备的唯一标识符是许多应用的基本需求之一。
推荐库:
• class-transformer
• @ranran/utilcode
使用三方库获取设备唯一标识符的一个优点是,即使卸载重装,该标识符依然保持不变。
5、支付宝SDK
对于支付功能,我们选择了 @cashier_alipay/cashiersdk。
注意事项: 测试时需使用真机,因为模拟器和预览器可能不支持。
6、Tab样式
为了实现美观的Tab布局,我们使用了 @zyc/tablayout。