Harmony NEXT:hvigorfile简易插件实践--实现添加编译时间功能

397 阅读3分钟

一、实现背景

在纯血鸿蒙项目中实现类似Android项目里,添加自定义属性到Build类,在业务代码中访问并打印该属性值,或添加打包属性给到编译产物命名,以达到区别产物版本的目地。本次实践添加的属性值为编译时间:BUILD_TIME

二、环境参数

  • OS: WINDOWS 10
  • IDE: DevEco Studio 5.0.0 Release,Build Version: 5.0.3.910, built on November 1, 2024
  • SDK: HarmonyOS 5.0.0 Release SDK, based on OpenHarmony SDK Ohos_sdk_public 5.0.0.71 (API Version 12 Release)

三、实现过程

1. 基本思路如下图:

image.png

2. 具体实现
2.1 自定义属性

在模块级build-profile.json5文件中增加自定义属性“BUILD_TIME” ,下方示例是将新增属性添加在buildOption节点下的。

注:自定义属性可以在buildOption、buildOptionSet、targets节点下的arkOptions子节点中通过增加buildProfileFields字段实现,自定义参数通过key-value键值对的方式配置,其中value取值仅支持number、string、boolean类型。

    {
      "apiType": "stageMode",
      "buildOption": {
        "arkOptions": {
          "byteCodeHar": false,
          "buildProfileFields": {
            "BUILD_TIME": ""
          }
        }
      },
      ...
      }
2.2 动态修改属性值

在同一模块hvigorfile.ts中新增‘getBuildTime()’插件,插件实现思路为:

  1. 先获取当前编译最新时间currentDate,格式化成需要的时间time
  2. 随后获取hvigor节点上下文harCtx。
  3. 从harCtx获取到当前模块生成BuildProfile的json文件(对应build-profile.json5)对象buildProfileJson
  4. 从buildProfileJson按json层级读取到buildProfileFields对象
  5. 给buildProfileFields新增属性BUILD_TIME重新赋值time
  6. 将更新后的buildProfileJson重新赋值给BuildProfile

插件实现如下:

    function getBuildTime(): HvigorPlugin {

        return {
            pluginId: 'getBuildTime',
            apply(node: HvigorNode) {
                // 插件主体
                const currentDate = new Date();
                const year = currentDate.getFullYear();
                const month = currentDate.getMonth() + 1; // 月份从0开始,需要加1
                const date = currentDate.getDate();
                const hours = currentDate.getHours();
                const minutes = currentDate.getMinutes();
                const seconds = currentDate.getSeconds();

                const time = `${year}-${month}-${date} ${hours}:${minutes}:${seconds}`
                console.log(`hello  getBuildTime  当前编译时间:${year}-${month}-${date} ${hours}:${minutes}:${seconds}`);

                // 获取har模块上下文信息
                // 如果是HAP或HSP,使用OHOS_HAP_PLUGIN/OHOS_HSP_PLUGIN
                const harCtx = node.getContext(OhosPluginId.OHOS_HAR_PLUGIN) as OhosHarContext
                const buildProfileJson = harCtx.getBuildProfileOpt()
                console.log(`hello  getBuildTime  build-profile:${harCtx.getBuildProfileOpt()}`);
                const buildProfileFields = buildProfileJson.buildOption.arkOptions.buildProfileFields
                buildProfileFields.BUILD_TIME =  time

                console.log(`hello  getBuildTime  BUILD_TIME:${buildProfileFields.BUILD_TIME}`);
                harCtx.setBuildProfileOpt(buildProfileJson)

            }
        }
    }

新增加的插件需要添加到plugins数组中:

    export default {
        system: harTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
        plugins:[getBuildTime()]         /* Custom plugin to extend the functionality of Hvigor. */
    }

所需的导入项如下:

    import { harTasks ,OhosPluginId } from '@ohos/hvigor-ohos-plugin';
    // 导入接口
    import { HvigorPlugin, HvigorNode } from '@ohos/hvigor';
2.3 在BuildProfile生成新增属性

当前有以下几种方式可以生成BuildProfile类文件:

  • 选中需要编译的模块,在菜单栏选择“Build > Generate Build Profile ${moduleName}”

  • 选中需要编译的模块,在菜单栏选择“Build > Make Module ${moduleName}”

  • 在Terminal中执行如下命令: hvigorw GenerateBuildProfile

    生成文件及属性位置如下图所示:

image.png

编译模块时,Build窗口会打印上面在hvigorfile.ts中使用console打印的内容,类似下图这样:

image.png 因此可以通过Build的打印输出调试hvigorfile.ts插件代码

2.4 在项目中使用新增属性

本次实践是将打包时间封装成了工具类,在模块初始化的时候调用工具类打印,代码如下:

    import BuildProfile from "../../../../BuildProfile"

    class BuildUtils {
      getBuildTime(){
        return BuildProfile.BUILD_TIME
      }
    }

    export const buildUtils = new BuildUtils()

使用时,类似这样:

    aboutToAppear(): void {
      Logger.info(TAG, 'aboutToAppear  SDK编译时间:'+buildUtils.getBuildTime())
      ...
      }
2.5 给模块version添加打包时间

在同一模块hvigorfile.ts中的‘getBuildTime()’插件末尾新增代码:

//新增编译时间到version末尾
const versionJson =  harCtx.getVersion()
const newVersion = versionJson+`.${date}${hours}${minutes}`
harCtx.setVersion(newVersion)
console.log(`hello  getBuildTime  newVersion:${newVersion}`);

更新代码后,点击右上角sync now,在IDE下方build窗口可看到输出带编译时间的version:

image.png

该模块生成har包,用IDE预览har包文件,可以查看到har内部oh-package.json5文件内verson属性已经成功修改: image.png

四、总结

  • 自定义属性不止限于buildTime,还可扩展切换环境功能,部分功能的裁减打包控制等等
  • har模块对应OhosHarContext,hsp对应OhosHspContext,hap对应OhosHapContext,需注意按模块类型区别使用。另:hsp生成的BuildProfile文件位置在build文件夹中
  • hvigor支持读取的配置文件包括
    • app.json5
    • module.json5
    • 每个hvigorNode中的build-profile.json5
    • 每个module下的oh-package.json5文件中的dependency、devDependency、dynamicDependency以及version。
  • 官方BuildProfile API查阅
  • 官方har对应context API查阅