鸿蒙系统中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
注意事项
- 兼容性:确保插件与 Hvigor 版本匹配。
- 性能:避免在插件中执行耗时操作,以免影响构建速度。
- 调试 :使用
hvigorw --debug
查看详细构建日志。
通过 HvigorPlugin
接口,开发者可以深度定制鸿蒙应用的构建流程,实现自动化代码检查、资源优化等高级功能。