解决思路:通过hvigorfile脚本开发构建插件,在插件中执行例如bat脚本等脚本程序,将资源下载到rawfile文件夹后再完成构建打包的工作。
实现示例:
@echo off
set "download_url=https://example.com/file.zip"
set "save_folder=./Downloads"
set "filename=file.zip"
:: 检查保存文件夹是否存在,如果不存在则创建
if not exist "%save_folder%" (
mkdir "%save_folder%"
)
:: 使用 PowerShell 下载文件
powershell -Command "(New-Object System.Net.WebClient).DownloadFile('%download_url%', '%save_folder%\%filename%')"
echo 文件下载完成,保存路径为:'%save_folder%/%filename%'
#!/bin/bash # 设置变量 download_url="https://example.com/file.zip" save_folder="./Downloads" filename="file.zip" # 创建保存目录(如果不存在) mkdir -p "$save_folder" # 检查系统中是否有 curl 或 wget,并选择其一进行下载 if command -v curl >/dev/null 2>&1; then echo "使用 curl 下载文件..." curl -L -o "$save_folder/$filename" "$download_url" elif command -v wget >/dev/null 2>&1; then echo "使用 wget 下载文件..." wget -O "$save_folder/$filename" "$download_url" else echo "错误:未找到 curl 或 wget,请安装其中一个工具。" exit 1 fi # 检查下载是否成功 if [ $? -eq 0 ]; then echo "文件下载完成,保存路径为:$(realpath "$save_folder/$filename")" else echo "下载失败!" exit 1 fi
然后将对应脚本文件放在需要更新rawfile目录文件的模块中,例如放在Entry模块的根目录,此时可以save_folder可改为./src/main/resources/rawfile。
import { hapTasks } from '@ohos/hvigor-ohos-plugin'; import { execSync } from 'node:child_process'; import util from 'node:util'; export function downloadFilePluginFunc(str?: string): HvigorPlugin { return { pluginId: 'DownloadFilePluginID01', apply(pluginContext): void { pluginContext.registerTask({ // 编写自定义任务 name: 'customTask1', run: (taskContext) => { let command = ''; const platform = process.platform; if (platform === 'win32') { command = 'downloadFile.bat'; } else { command = 'sh downloadFile.sh'; } const workingDirectory = __dirname; try { const output = execSync(command, { cwd: workingDirectory }); console.info(`文件下载成功,输出: ${output.toString()}`); } catch(e) { console.info(`文件下载失败,输出: ${e.toString()}`); } }, // 确认自定义任务插入位置 dependencies: ['default@GenerateMetadata'], postDependencies: ['default@ProcessResource'] }) } } } export default { system: hapTasks, /* Built-in plugin of Hvigor. It cannot be modified. */ plugins: [downloadFilePluginFunc()] /* Custom plugin to extend the functionality of Hvigor. */ }

以上运行结果说明脚本执行成功,可以通过自定义构建任务获取云端文件新增或更新到rawfile文件夹中。