当前位置: 首页 > article >正文

鸿蒙编译框架插件HvigorPlugin接口的用法介绍

鸿蒙系统中HvigorPlugin接口实现自定义编译插件,实现编译前后自定义功能。

在鸿蒙(HarmonyOS)开发中,HvigorPlugin 是用于扩展 Hvigor 构建工具功能的接口。通过实现此接口,开发者可以自定义构建任务、修改构建流程或集成第三方工具。以下是核心概念和示例:


1. HvigorPlugin 接口定义

interface HvigorPlugin {
  /**
   * 插件初始化方法
   * @param hvigorContext Hvigor 上下文,提供构建配置、任务管理等 API
   */
  apply(hvigorContext: HvigorContext): void;
}

2. 实现自定义插件

步骤 1:创建插件类
// CustomPlugin.ts
import { HvigorPlugin, HvigorContext, Task } from '@ohos/hvigor';

export class CustomPlugin implements HvigorPlugin {
  apply(context: HvigorContext) {
    // 在此注册自定义任务或修改构建流程
    const taskName = 'customTask';
    context.taskRegistry.registerTask(taskName, this.customTask);
  }

  private customTask: Task = async (context) => {
    console.log('执行自定义任务');
    // 在此实现任务逻辑(如文件处理、代码生成等)
  };
}
步骤 2:在 hvigorfile.ts 中应用插件
// hvigorfile.ts
import { Hvigor } from '@ohos/hvigor';
import { CustomPlugin } from './CustomPlugin';

export default function (hvigor: Hvigor) {
  hvigor.applyPlugin(new CustomPlugin());
}

3. 常用 API

通过 HvigorContext 可访问以下核心功能:

| API 类别 | 方法/属性 | 说明

| |-----------------------|--------------------------|-----------------------------|

任务管理 | taskRegistry | 注册/获取构建任务 |

模块配置 | getModuleConfig() | 获取当前模块的配置信息 |

依赖管理 | dependencies | 管理模块依赖 |

生命周期钩子 | beforeBuild/afterBuild| 在构建前后插入自定义逻辑 |


4. 实战示例:

4.1 自定义编译前添加文件压缩任务
// ZipPlugin.ts
import { HvigorPlugin, HvigorContext, Task } from '@ohos/hvigor';
import * as fs from 'fs';
import * as zlib from 'zlib';

export class ZipPlugin implements HvigorPlugin {
  apply(context: HvigorContext) {
    context.taskRegistry.registerTask('zipAssets', this.zipAssetsTask);
  }

  private zipAssetsTask: Task = async (context) => {
    const assetsDir = context.getModuleConfig().path.assets;
    const outputPath = `${assetsDir}/compressed.zip`;

    // 压缩 assets 目录
    const zipStream = fs.createWriteStream(outputPath);
    const gzip = zlib.createGzip();
    
    fs.createReadStream(assetsDir)
      .pipe(gzip)
      .pipe(zipStream)
      .on('finish', () => {
        console.log('资源压缩完成');
      });
  };
}
4.2 自定义插件动态更换Dependencies依赖的har包
import { hapTasks, OhosHapContext, OhosPluginId, Target  } from '@ohos/hvigor-ohos-plugin';
import { hvigor, HvigorNode, HvigorPlugin } from '@ohos/hvigor';

/**
 * 判断是否为定制的target
 * @param targetName flavor target 名称。
 * @returns
 */
function isGMTarget(targetName: string): boolean {
    if (targetName.match('gm') || targetName.match('sm')) {
        return true;
    } else {
        return false;
    }
}

export function customPlugin(): HvigorPlugin {
    let gmSdkPath = 'file:./libs/sdk_GM-v1.0.202503102040.har';
    //let defaultSdkPath = 'file:./libs/sdk_standard-v1.0.202503102040.har';
    return {
        pluginId: 'customPlugin',
        async apply(currentNode: HvigorNode): Promise {
            const hapContext = currentNode.getContext(OhosPluginId.OHOS_HAP_PLUGIN) as OhosHapContext;
            hapContext?.targets((target: Target) => {
                const targetName = target.getTargetName();
                console.log('customPlugin: targetName=', targetName);
                //声明依赖sdk文件路径
                let customsdkPath = '';
                const dependency = hapContext.getDependenciesOpt();
                if (isGMTarget(targetName)) {
                    // 新增 或者 修改依赖
                    //国密 target,修改'testsdk'依赖har文件为国密版本sdk
                    customsdkPath = gmSdkPath;
                    //dependency['testsdk'] = gmSdkPath;
                    // 删除依赖
                    //delete dependency['har1'];
                } else if (targetName === 'default') {
                    //默认 target:修改'testsdk'依赖har文件为国密版本sdk
                    //customsdkPath = defaultSdkPath;
                } else {
                    //默认'testsdk'依赖har文件为标密版本sdk
                    //customsdkPath = defaultSdkPath;
                }
                //修改奇安信VPNSDK的依赖文件路径
                if (customsdkPath !== undefined && customsdkPath !== "") {
                    console.log('customPlugin: Modify dependencies[testsdk]=', customsdkPath);
                    dependency['testsdk'] = customsdkPath;
                    //把修改之后的插件设置回 entry/oh-package.json5文件中的'dependencies'
                    hapContext.setDependenciesOpt(dependency)
                }
            });
        }
    };
}

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

5. 运行自定义任务

# 执行注册的自定义任务
hvigorw customTask

# 或通过模块名指定
hvigorw ModuleName:customTask

注意事项

  1. 兼容性:确保插件与 Hvigor 版本匹配。
  2. 性能:避免在插件中执行耗时操作,以免影响构建速度。
  3. 调试:使用 hvigorw --debug 查看详细构建日志。

通过 HvigorPlugin 接口,开发者可以深度定制鸿蒙应用的构建流程,实现自动化代码检查、资源优化等高级功能。


http://www.kler.cn/a/583979.html

相关文章:

  • 蓝桥杯备考:数据结构堆之 除2!
  • STM32Cubemx-H7-9-串口接受不定长度数据并识别
  • 解决 VSCode SSH 连接报错:“REMOTE HOST IDENTIFICATION HAS CHANGED” 的问题
  • Nginx 多协议代理功能(Nginx Multi Protocol Proxy Function)
  • windows11 LTSC 24h2 访问NAS问题的安全高效解决
  • C语言:计算并输出三个整数的最大值 并对三个数排序
  • 图解AUTOSAR_CP_ServiceDiscovery
  • Unix 域套接字(本地套接字)
  • NLP常见任务专题介绍(4)-ConditionalGeneration和CasualLM区别
  • 关于Playwright和Selenium 的区别和选择
  • nginx部署使用【常用命令】
  • C++时间复杂度详解
  • Blackbox.Ai体验:AI编程插件如何提升开发效率
  • Docker 基础命令 - 以 Nginx 实战总结
  • 在Electron-Vue中实现macOS风格自定义标题栏
  • 数据结构与算法效率分析:时间复杂度与空间复杂度详解(C语言)
  • 【OpenCV C++】存图,如何以时间命名,“年月日-时分秒“产生唯一的文件名呢?“年月日-时分秒-毫秒“ 自动检查存储目录,若不存在自动创建存图
  • 2024年第十五届蓝桥杯软件C/C++大学A组——五子棋对弈
  • 前缀和(例题)
  • availability() missing 2 required positional arguments: ‘host‘ and ‘d‘ 怎么处理