[经验分享] OpenHarmony应用开发引入开源JS库 原创 精华

深开鸿_王石 显示全部楼层 发表于 2024-5-6 08:51:03

OpenHarmony-TPC

OpenHarmony-TPC(Third Party Components)用于汇集OpenHarmony系统上的开源三方库,帮助应用开发者快速开发OpenHarmony应用。OpenHarmony-TPC由OpenHarmony知识体系工作组下属的OpenHarmony三方库SIG主导。

OpenHarmony三方库中心仓

创建三方库

开发完库模块后,选中模块名,然后通过DevEco Studio菜单栏的Build > Make Module \${libraryName}进行编译构建,生成HAR。HAR可用于工程其它模块的引用,或将HAR上传至ohpm仓库,供其他开发者下载使用。若部分源码文件不需要打包至HAR/HSP中,可通过创建.ohpmignore文件,配置打包时要忽略的文件/文件夹。


HAR(Harmony Archive)是静态共享包,可以包含代码、C++库、资源和配置文件。通过HAR可以实现多个模块或多个工程共享ArkUI组件、资源等相关代码。HAR不同于HAP,不能独立安装运行在设备上,只能作为应用模块的依赖项被引用。

  • 使用场景
    • 作为二方库,发布到OHPM私仓,供公司内部其他应用使用。
    • 作为三方库,发布到OHPM中心仓,供其他应用使用。
  • HAR开发约束限制
    • HAR不支持UIAbility、ExtensionAbility组件和pages页面。
    • HAR不支持在build-profile.json5文件的buildOption中配置worker。
    • FA模型与Stage模型的HAR不支持相互引用。
    • Stage模型的HAR,不能引用AppScope内的内容。在编译构建时AppScope中的内容不会打包到HAR中,因此会导致HAR资源引用失败。

开发介绍

  1. 创建一个工程

    image.png

  2. 工程里加模块

    image.png

  3. 选择staticlibrary,就是静态库

    image.png

  4. 在主工程里导入library工程

    image.png

  5. 下载移植对象源:GitHub - brix/crypto-js: JavaScript library of crypto standards.

    // 下载源码
    # git clone https://github.com/brix/crypto-js.git
    
    // 拷贝 js 到 项目里,把src里的js文件拷贝到工程里的library/src/main/js目录里

    image.png

  6. 修改代码导出控件,方法

    import sha256 from '../../../js/sha256'
    ...
    
    @Component
    export struct MainPage {
      @State message: string = 'Har Two Test';
    
      build() {
        Row() {
          Column() {
            Text(this.message)
              .fontSize(50)
              .fontWeight(FontWeight.Bold)
          }
          .width('100%')
          .onClick(()=>{
            hilog.info(0x0000, 'testTag', 'Hello Har Sha256 = %{public}s', sha256("123456").toString());
          })
        }
        .height('30%')
      }
    }
    

    此时会出两个错误:

    • File 'D:/xxx/cryptojssample/library/src/main/js/sha256.js' is not a module. 啥意思,就是这是源码,没有export的模块,解决方法如下:

      // 在源码下载路径下
      # npm install (如果安装报错,可以试试 npm install --force)
      # npm run build
      // 然后可以把build目录里的代码拷贝到之前的 library/src/main/js 目录里
    • ReferenceError: unescape is not defined 啥意思,就是有个方法 unexcape 的方法没有定义。查找后发现,在 JavaScript 中,unescape() 函数已经被弃用,并且在严格模式下,或在某些环境中(如 Node.js)可能会导致 ReferenceError。相反,你可以使用 decodeURI()decodeURIComponent() 函数来替代 unescape()

      image.png

      所以对应代码修改为:

      return Latin1.parse(decodeURIComponent(encodeURIComponent(utf8Str)));
      
      // 打印输出
      Hello Har Sha256 = 8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92
  7. 对外暴露

    • 修改Index.ets,暴露CryptoJS

      import CryptoJS from "./src/main/js"
      
      export { CryptoJS }
      
      export { MainPage } from './src/main/ets/components/mainpage/MainPage'
    1. 测试应用使用接口
    • 修改HAP里的Index.ets接口

      import { MainPage, CryptoJS } from 'library'
      import hilog from '@ohos.hilog';
      
      @Entry
      @Component
      struct Index {
        @State message: string = 'Hello World';
      
        build() {
          Row() {
            Column() {
              // 导入HAR包里的界面
              MainPage()
              Text(this.message)
                .fontSize(50)
                .fontWeight(FontWeight.Bold)
            }
            .width('100%')
            .onClick(()=>{
              // 导入HAR包里的接口
              hilog.info(0x0000, 'testTag', 'Index HmacSHA1 : %{public}s', CryptoJS.HmacSHA1("Message", "Key").toString());
            })
          }
          .height('100%')
        }
      }
    • 打印输出

      Index HmacSHA1 : c0334f18a5fbca1030ae7d7863ceca0206ce1712
    1. ut进行接口测试
    • 增加测试用例

      // 导入库
      import { CryptoJS } from 'library'
      
      // 加测试用例
      it('assertHmacSHA1', 0, () => {
          // Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function.
          hilog.info(0x0000, 'testTag', '%{public}s', 'it begin');
          let c: string = CryptoJS.HmacSHA1("Message", "Key").toString();
          let resc = 'c0334f18a5fbca1030ae7d7863ceca0206ce1712';
          // Defines a variety of assertion methods, which are used to declare expected boolean conditions.
          expect(c).assertEqual(resc);
      })
    1. 三方库发布
    • 发布的三方库必须遵循以下规则:

      • 发布的三方库必须有明确的功能。
      • 发布的三方库库命名需规范。 请参考OpenHarmony 三方库名称指南
      • 发布的三方库需包含Readme文件。 建议ReadMe中包含简介,下载安装,所需权限,使用示例,接口说明,约束与限制(支持API几,SDK版本),目录结构,贡献代码,开源协议。 之所以有这些要求,也是便于开发者使用。
      • 发布的三方库必须包含License 文件。
      • 发布的三方库需包含ChangeLog文件。
      • 发布的三方库版本命名需规范。 请参照OpenHarmony-TPC版本命名指导
    • 三方库.d.ts生成

      // 安装 移植的三方库
      npm install crypto-js
      
      // 生成 d.ts文件
      wshi@ubuntu:~$ dts-gen -m crypto-js -f crypto-js.d.ts
      Wrote 3412 lines to crypto-js.d.ts.
      
      // 对应 d.ts文件内容
      /** Declaration file generated by dts-gen */
      
      export const algo: {
          AES: {
              $super: {
                  $super: {
                      $super: {
                          $super: {
                              clone: any;
                              create: any;
                              extend: any;
                              init: any;
                              mixIn: any;
      。。。
    • 导出package,配置项的设置请参考oh-package.json5配置说明

      {
        "types": "index.d.ts",
        "keywords": [
          "crypto-js",
          "OpenHarmony",
          "HarmonyOS"
        ],
        "author": "xxx",
        "description": "JavaScript library of crypto standards.Nowadays, NodeJS and modern browsers have a native Crypto module. The latest version of CryptoJS already uses the native Crypto module for random number generation, since Math.random() is not crypto-safe. Further development of CryptoJS would result in it only being a wrapper of native Crypto. Therefore, development and maintenance has been discontinued, it is time to go for the native crypto module.",
        "ohos": {
          "org": "opensource"
        },
        "main": "index.ts",
        "repository": "https://gitee.com/openharmony-sig/crypto-js",
        "type": "module",
        "version": "2.0.4-rc.1",
        "dependencies": {},
        "tags": [
          "Tools",
          "Security"
        ],
        "license": "MIT",
        "devDependencies": {},
        "name": "@ohos/crypto-js"
      }

      总结

      创建三方库的文档如下:

©著作权归作者所有,转载或内容合作请联系作者

您尚未登录,无法参与评论,登录后可以:
参与开源共建问题交流
认同或收藏高质量问答
获取积分成为开源共建先驱

Copyright   ©2023  OpenHarmony开发者论坛  京ICP备2020036654号-3 |技术支持 Discuz!

返回顶部