参考unity PBXProject做了一个鸿蒙打包后处理的小工具,比较简单。

之前的项目在导出鸿蒙工程以后要修改Deveco很多地方,基本上都是这里插入一些代码,改起来很繁琐,我也比较懒,不喜欢做重复性的事情,就利用空闲时间写了个小工具。

首先讲思路,unity提供了很多预处理和后处理,方便在恰当的时机做恰当的事情,这里就用到了PostProcessBuild(打包后处理),unity提供了两个参数buildTarget和pathToBuilpathtProject,这两个参数我就不多解释了,构建平台和构建之后的Deveco路径有了,那就方便了,修改哪个文件,直接在pathToBuilpathtProject后面拼接要修改的文件路径,然后按行读取脚本就可以了,就可以查找要修改的地方。

修改的话,一般只有增删改这三种方式,增加的话可能会在要找的代码片段上面或者下面添加,所以定义了4种方式。

public enum OprType
{
    AddUp,//在对应文本上方加入
    AddBelow,//在对应文本下方加入
    Del,
    Replace
}

我之前的项目还有根据开发模式和Release模式配置不同的代码,可以定义一个buildType表示。

public enum BuildType
{
    Development,
    Release,
    All
}

既然要修改具体的脚本,那就要定义脚本路径,还有修改这个脚本的方式,要查找的原始内容和可能要替换的新内容,于是可以这样定义

public class FileOperation
{
    public BuildType buildType;
    public OprType oprType;
    public string oriContent;
    public string newContent;
}

一个脚本可能要修改多次,这里就用到了json,可读性比较高

[Serializable]
public class OpenHarmonyBuildConfig
{
    public string filePath;
    public List<FileOperation> fileOperation;
}

[Serializable]
public class OpenHarmonyBuildConfigs
{
    public List<OpenHarmonyBuildConfig> buildConfigs;
}

 最后json配置如下

{
    "buildConfigs":[
    {
        "filePath":"entry/src/mian/ets/pages/Index.ets",
        "fileOperation":[
            {
                "buildType":0,
                "oprType":0,
                "oriContent":"",
                "newContent":""
            },
            {
                "buildType":0,
                "oprType":1,
                "oriContent":"",
                "newContent":""
            },
            {
                "buildType":0,
                "oprType":2,
                "oriContent":"",
                "newContent":""
            },
            {
                "buildType":0,
                "oprType":3,
                "oriContent":"",
                "newContent":""
            }
        ]
    }
    ]
}

下面就是根据配置遍历脚本,找到要修改的地方进行相应的处理,例如在某代码上面添加一行

private static void AddUp(string oriContent, string newContent)
{
    for (int i = 0; i < strContents.Length; i++)
    {
        if (strContents[i].Contains(oriContent))
        {
            strContents[i] = string.Format("{0}\n{1}", newContent, strContents[i]);
            break;
        }
    }
}

完整代码在这里:https://gitee.com/jin_xin_true/open-harmony-post-process-build

当然也可以考虑把替换好的脚本保存到其他目录,利用后处理进行替换也行。打包安卓的话也可以用类似的方式,ios的话已经有PBXProject了,我就不说了。

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐