写点什么

【HarmonyOS】关于鸿蒙原生项目多环境的配置和管理

  • 2025-03-21
    安徽
  • 本文字数:3812 字

    阅读完需:约 13 分钟

开发语言:ArkTs


开发工具:DevEco Studio 5.0.0 Release


API 版本:API 12


demo 演示Gitee:harmony-multiEnv.git


在开发中为了数据隔离和开发规范,一般情况下都需要配置多环境,方便开发、测试、部署,比如:dev、test、sit、gray、release 等,不同公司在多环境使用上不尽相同,本文使用 dev、test、release 三个环境演示鸿蒙的多环境。

一、开发工具配置多环境

1、环境切换入口

DevEco Studio开发工具的工具条中,点击瞄准镜图标即可进行环境的切换。


2、配置签名(debug 和 release)

打开工具栏File - Project Structure - Project - Signing Configs,默认工程只有一个default签名配置,可点击+-添加删除配置,签名配置完成后,在工程目录下的build-profile.json5文件中可查看signingConfigs字段的签名配置。<br>本文演示配置debugrelease两个签名。



{  "app": {    "signingConfigs": [      {        "name": "debug",        "type": "HarmonyOS",        "material": {          "certpath": "./debug.cer",          "storePassword": "xxxx",          "keyAlias": "debugKey",          "keyPassword": "xxxx",          "profile": "./debug.p7b",          "signAlg": "SHA256withECDSA",          "storeFile": "./debug.p12"        }      },      {        "name": "release",        "type": "HarmonyOS",        "material": {          "certpath": "./release.cer",          "storePassword": "xxxx",          "keyAlias": "debugKey",          "keyPassword": "xxxx",          "profile": "./release.p7b",          "signAlg": "SHA256withECDSA",          "storeFile": "./release.p12"        }      }    ],    "products": [      //...    ],    "buildModeSet": [      //...    ]  },  "modules": [     //...  ]}
复制代码

3、创建多环境配置文件

entry/src/main/resources/rawfile目录下创建三个环境对应的配置文件,取名为app_config_dev.jsonapp_config_test.jsonapp_config_release.json。<br>每个配置文件包含相同的三个字段:<br>ServerUrl表示请求服务器地址、ResourceUrl表示资源服务器地址、release表示是否为生产环境。



{  "ServerUrl": "https://www.dev.com/api/",  "ResourceUrl": "https://www.dev.com/resource/",  "release": false}
复制代码

4、配置工程支持多环境

  • 配置products



在工程目录下的build-profile.json5文件中配置products字段,可在默认的数据中新增arkOptions - buildProfileFields - APP_CONFIG字段,用来配置每个环境对应的配置文件。APP_CONFIG为自定义,可自行改名。


  • 配置modules



在工程目录下的build-profile.json5文件中配置modules字段,在默认的数据targets - applyToProducts中新增步骤 1 中的各个环境。



{  "app": {    "signingConfigs": [      // ...     ],    "products": [      {        "name": "default",        "signingConfig": "debug",        "compatibleSdkVersion": "5.0.0(12)",        "runtimeOS": "HarmonyOS",        "buildOption": {          "strictMode": {            "caseSensitiveCheck": true,            "useNormalizedOHMUrl": true          },          "arkOptions": {            "buildProfileFields": {              "APP_CONFIG": "app_config_release.json"            }          }        }      },      {        "name": "dev",        "signingConfig": "debug",        "compatibleSdkVersion": "5.0.0(12)",        "runtimeOS": "HarmonyOS",        "buildOption": {          "strictMode": {            "caseSensitiveCheck": true,            "useNormalizedOHMUrl": true          },          "arkOptions": {            "buildProfileFields": {              "APP_CONFIG": "app_config_dev.json"            }          }        }      },      {        "name": "test",        "signingConfig": "debug",        "compatibleSdkVersion": "5.0.0(12)",        "runtimeOS": "HarmonyOS",        "buildOption": {          "strictMode": {            "caseSensitiveCheck": true,            "useNormalizedOHMUrl": true          },          "arkOptions": {            "buildProfileFields": {              "APP_CONFIG": "app_config_test.json"            }          }        }      },      {        "name": "release",        "signingConfig": "release",        "compatibleSdkVersion": "5.0.0(12)",        "runtimeOS": "HarmonyOS",        "buildOption": {          "strictMode": {            "caseSensitiveCheck": true,            "useNormalizedOHMUrl": true          },          "arkOptions": {            "buildProfileFields": {              "APP_CONFIG": "app_config_prod.json"            }          }        }      }    ],    "buildModeSet": [      // ...    ]  },  "modules": [    {      "name": "entry",      "srcPath": "./entry",      "targets": [        {          "name": "default",          "applyToProducts": [            "default",            "dev",            "test",            "release"          ]        }      ]    }  ]}
复制代码

5、获取当前环境配置信息

创建AppConfig.ets文件,用来获取环境配置文件,并解析文件数据。BuildProfile为使用开发工具切换环境后,build工程生成的编译文件,用来获取当前环境下的环境配置信息。



import BuildProfile from 'BuildProfile'import { HashMap } from '@kit.ArkTS';

export class AppConfig { // 单例 private static config: AppConfig; static getInstance(): AppConfig { if (AppConfig.config === undefined) { AppConfig.config = new AppConfig(); } return AppConfig.config; }
// 请求服务器地址 public baseServerUrl: string = ''; // 资源服务器地址 public resourceServerUrl: string = ''; // 是否为生产环境 public isRelease: boolean = true; // 记录context,后面方法使用 private context?: Context;
/** * 初始化方法 */ init(context: Context, filePath?: string): void { try { this.context = context; // 配置文件路径(从环境配置中获取) let configFilePath: string = filePath ?? BuildProfile.APP_CONFIG; // 解析配置文件 let bytes: Uint8Array = context.resourceManager.getRawFileContentSync(configFilePath); let content = this.bytesToString(bytes); let jsonObj: object = JSON.parse(content); // 重新组装map对象 let configMap: HashMap<string, string|boolean> = new HashMap(); let keys: string[] = Object.keys(jsonObj); keys.forEach(key => { let value: string|boolean = jsonObj[key]; configMap.set(key, value); }) // 获取配置文件字段值 this.baseServerUrl = configMap.get("ServerUrl") as string; this.resourceServerUrl = configMap.get("ResourceUrl") as string; this.isRelease = configMap.get("release") as boolean; } catch (e) {
} } /** * Uint8Array类型转换String * @param input bytes数据 * @returns 返回字符串 */ public static bytesToString(input: Uint8Array): string { let output: string = ''; try { let textDecoder = util.TextDecoder.create("utf-8",{ignoreBOM: true}); output = textDecoder.decodeToString(input , {stream: false}); } catch (err) {} return output; }}
复制代码

6、生效当前环境信息

本文使用AbilityStage作为初始化环境信息的类,关于AbilityStage的介绍可查看官方文档介绍。


  • 创建HMAbilityStage.ets类,继承AbilityStage,重写onCreate()方法。

  • entry/src/main/module.json5文件中的配置srcEntry字段值为HMAbilityStage.ets文件的相对路径。



{  "module": {    "name": "entry",    "type": "entry",    "srcEntry": "./ets/stage/HMAbilityStage.ets",    "description": "$string:module_desc",    "mainElement": "EntryAbility",    "deviceTypes": [      "phone",      "tablet",      "2in1"    ],    "deliveryWithInstall": true,    "installationFree": false,    "pages": "$profile:main_pages",    // ...  }}
复制代码

二、APP 内动态切换环境

创建环境切换页面,用于切换不同环境,切换环境时再次调用AppConfig的初始化方法,传入指定配置文件路径即可。


AppConfig.getInstance().init(getContext(this), 'app_config_test.json')
复制代码


示例中未进行数据持久化记录上次选中的环境,真正项目中可本地存储环境,下次启动使用切换后的环境配置信息


结尾

如大家发现文章描述有问题或有更好的方案,还请评论回复,一起探讨学习,感谢!

发布于: 刚刚阅读数: 5
用户头像

还未添加个人签名 2025-03-18 加入

还未添加个人简介

评论

发布
暂无评论
【HarmonyOS】关于鸿蒙原生项目多环境的配置和管理_鸿蒙_走向菜鸟的菜鸟_InfoQ写作社区