【坚果派】JS 开源库适配 OpenHarmony 系列——第一期实操


1. 为什么适配 JS 开源库
由于 OpenHarmony 应用是基于 ArkTS 开发,而 ArkTS 是在保持 TypeScript(简称 TS)基础语法风格的基础上,对 TS 的动态类型特性施加更严格的约束,引入静态类型。因此在开发 OpenHarmony 三方库时,建议首选在成熟的 JS/TS 开源三方库上开发。
2. 选择哪个 JS 开源库合适
JS/TS 开源三方库的选择需遵循易用性、实用性、维护性、扩展性等特性,通常方法是在 github/npm 上按照特性和语言搜索,找到 star、fork 数量较高的,且开源协议友好的 JS/TS 开源三方库进行适配。
3. 如何进行 JS 开源库适配
由于 OpenHarmony 开发框架中的 API 不完全兼容 V8 运行时的 Build-In API,因此建议在适配 JS 三方库前,使用js-e2e扫描三方库,检查是否存在 node.js/web 内置模块的依赖。
js-e2e 工具时基于 eslint 进行封装,可分析出 JS 库代码对 node.js/web 浏览器的内置模块、对象的依赖及兼容 ES 标准版本,使用该工具,可以快速知道该库是否依赖 node.js/web 内置模块。
如果扫描结果不依赖 node.js/web 内置模块,那么,这个库将比较轻松地适配。如果大量依赖 node.js/web 内置组件,这时可能需要 fork 源库代码,进行侵入式修改,或者再找是否存在更适合的其他三方库。
注:扫描时需同时扫描 package.json 文件中 dependencies 标签中直接依赖和间接依赖,因为发布 OpenHarmony 三方库中心仓时,需要将依赖的组件都发布。建议使用 npm insall 下载所有依赖的代码后,一起扫描查看结果。
3.1 luxon 开源库信息
在 npm 中心仓库查看用于处理日期和时间的目标库 luxon 信息,包括开源仓库地址,主页地址,版本,协议,文件大小,总文件数,最后发布时间等。

在 OpenHarmony 中心仓搜索是否存在 luxon 目标库。

在 luxon 源代码仓库查看 star 和 fork 数量,查看是否被经常使用和经常被维护。
luxon 仓库:https://github.com/moment/luxon

3.2 JS 三方库扫描工具介绍
js-e2e 是基于 eslint 进行封装、配置规则,用于分析 JS 库代码对 NodeJS 和 Web 浏览器的内置模块、对象的依赖及兼容 ES 标准版本的工具,支持检查指定源码目录和指定三方库的兼容性。
3.2.1 使用 git 工具同步 js-e2e 代码

3.2.2 安装 npm 依赖包

3.2.3 安装自定义的 eslint 输出报告 formatter,包含 csv、csvsimple、vscode、vscodesimple

3.2.4 执行检查命令

3.3 适配 luxon 三方库
使用 DevEco Studio 开发者工具,创建 OpenHarmony 应用工程。

在工程中新建 Module,选择“Static Library”模板。

移除 library 模块 src/main/ets 目录中的 components 目录,删除 Index.ets 文件中的代码。
直接复制 js-e2e 工具检查时下载的 luxon 包(temp/node_modules/luxon),并将 src 目录中的文件复制到 library 模块的 src/main/ets/lib 目录下。

5)修改 Index.ets 文件为其他开发者提供调用接口。

在 oh-package.json5 中完善三方库信息,如名称、简介、版本、开源协议、作者、关键字等。

在工程目录中选中三方库名称,单击菜单栏中的 Build > Make Module ‘library’编译构建生成三方库 HAR 包,HAR 包可在模块下的 build 目录下获取,包格式为*.har。

3.4 验证 luxon 三方库
打开 entry/oh-package.json5 配置文件,在 dependencies 标签中引入 luxon 三方库,并单击 Sync Now 进行同步。

打开 pages/Index.ets 页面文件,引入 luxon 三方库并显示当前日期。

至此,简单的 JS 开源三方库适配 OpenHarmony 已经完成了,下节我们将推出如何将讲解如何进行 XTS 测试,OpenHarmony 三方库发布标准,适配的三方库发布到 OpenHarmony 三方库中心仓以及如何贡献到 OpenHarmony-TPC。
版权声明: 本文为 InfoQ 作者【白晓明】的原创文章。
原文链接:【http://xie.infoq.cn/article/c45dfb08a5efecd8ac7e0ff05】。
本文遵守【CC BY-NC-SA】协议,转载请保留原文出处及本版权声明。
评论