HarmonyOS鸿蒙Next中自定义打包文件名,如何删除同文件夹存在的安装包

HarmonyOS鸿蒙Next中自定义打包文件名,如何删除同文件夹存在的安装包

在hvigorfile.ts配置

import { hapTasks, OhosHapContext, OhosPluginId } from '@ohos/hvigor-ohos-plugin'
import { hapPlugin } from '@hadss/hmrouter-plugin';
import { getNode } from '@ohos/hvigor'
import { hvigor } from '@ohos/hvigor'

const entryNode = getNode(__filename)
const appContext = hvigor.getRootNode().getContext(OhosPluginId.OHOS_APP_PLUGIN) as OhosAppContext
const appJsonOpt = appContext.getAppJsonOpt()
const versionName = appJsonOpt['app']['versionName']
entryNode.afterNodeEvaluate(node => {
    const hapContext = node.getContext(OhosPluginId.OHOS_HAP_PLUGIN) as OhosHapContext
    if (hapContext && hapContext.getBuildProfileOpt) {
        const buildProfile = hapContext.getBuildProfileOpt()
        const product = buildProfile.targets[0]
        product['output'] = {
            "artifactName": "com.xx.xxx-hm-" + versionName + '_' + getTime() + '_' + appContext.getBuildMode(),
        }
        hapContext.setBuildProfileOpt(buildProfile)
    }
})

function getTime(): string {
    let date = new Date()
    let year = date.getFullYear()
    let month = (date.getMonth() + 1).toString().padStart(2, '0')
    let day = date.getDate().toString().padStart(2, '0')
    let hours = date.getHours().toString().padStart(2, '0')
    let minutes = date.getMinutes().toString().padStart(2, '0')
    return `${year}-${month}-${day}_${hours}_${minutes}`
}

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

实现了自定义安装包文件名,但是每次运行都会生成一个新的包,如何添加配置使得运行的时候先删除文件夹下其它安装包再生成


更多关于HarmonyOS鸿蒙Next中自定义打包文件名,如何删除同文件夹存在的安装包的实战教程也可以访问 https://www.itying.com/category-93-b0.html

2 回复

开发者您好,可以在代码中加入deleteOldApp()方法,在构建之前删除旧的目标产物。

参考以下示例代码:

import { appTasks, OhosPluginId } from '@ohos/hvigor-ohos-plugin';
import { hvigor } from '@ohos/hvigor'
import * as fs from 'fs';
import * as path from 'path';

// 定义要删除的文件路径和文件格式
const dir = 'D:/Program/HarmonyProject/AAAA/Canvas/build/outputs/default'; // 替换为你的目标路径
const ext = '.app'; // 要删除的文件格式

hvigor.afterNodeEvaluate((hvigorNode)=>{
    const context = hvigorNode.getContext(OhosPluginId.OHOS_APP_PLUGIN)
    if (context && context.getBuildProfileOpt) {
        const buildProfile = context.getBuildProfileOpt();
        const products = buildProfile.app.products;
        deleteOldApp(dir, ext)
        for (const product of products) {
            if (product.name === context.getCurrentProduct().productBuildOpt.name) {
                product["output"]={
                    "artifactName": "app-v1.0.3-" + getTime()
                }
            }
        }
        context.setBuildProfileOpt(buildProfile);

    }
})

function deleteOldApp(dir: string, ext: string) {
    if (!fs.existsSync(dir)) {
        console.error(`Directory does not exist: ${dir}`);
        return;
    }
    fs.readdir(dir, { withFileTypes: true }, (err, files) => {
        if (err) {
            console.error(`Error occurred while reading directory ${dir}:`, err);
            return;
        }
        files.forEach(file => {
            console.log(file.name)
            const filePath = path.join(dir, file.name);
            if (file.name.endsWith(ext)) {
                // 如果是目标文件,删除
                fs.unlink(filePath, err => {
                    if (err) {
                        console.error(`Error occurred while deleting file ${filePath}:`, err);
                    } else {
                        console.log(`Deleted file: ${filePath}`);
                    }
                });
            }
        });
    });
}

function getTime(): string {
    let date = new Date()
    let year = date.getFullYear()
    let month = (date.getMonth() + 1).toString().padStart(2, '0')
    let day = date.getDate().toString().padStart(2, '0')
    let hours = date.getHours().toString().padStart(2, '0')
    let minutes = date.getMinutes().toString().padStart(2, '0')
    return `${year}-${month}-${day}_${hours}_${minutes}`
}

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

更多关于HarmonyOS鸿蒙Next中自定义打包文件名,如何删除同文件夹存在的安装包的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中,自定义打包文件名并删除同文件夹存在的安装包,可以通过以下步骤实现:

  1. 自定义打包文件名:在build.gradle文件中,使用outputFileName属性自定义APK文件名。例如:

    android {
        applicationVariants.all { variant ->
            variant.outputs.all {
                outputFileName = "MyApp-${variant.versionName}.apk"
            }
        }
    }
    
  2. 删除旧安装包:在打包前,使用Groovy脚本删除同文件夹下的旧安装包。例如:

    task deleteOldApks(type: Delete) {
        delete fileTree(dir: 'outputs/apk', include: '*.apk')
    }
    tasks.whenTaskAdded { task ->
        if (task.name == 'assembleRelease') {
            task.dependsOn deleteOldApks
        }
    }
    

这样,每次打包时都会删除旧的安装包,并生成新的自定义文件名APK。

回到顶部