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

走向菜鸟的菜鸟
发布于 2025-3-13 10:29
浏览
0收藏

开发语言: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开发工具的工具条中,点击瞄准镜图标即可进行环境的切换。
【HarmonyOS】【高级】关于鸿蒙原生项目多环境的配置和管理-鸿蒙开发者社区

2、配置签名(debug和release)

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

本文演示配置debugrelease两个签名。

【HarmonyOS】【高级】关于鸿蒙原生项目多环境的配置和管理-鸿蒙开发者社区

{
  "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": [
     //...
  ]
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.

3、创建多环境配置文件

entry/src/main/resources/rawfile目录下创建三个环境对应的配置文件,取名为app_config_dev.jsonapp_config_test.jsonapp_config_release.json

每个配置文件包含相同的三个字段:

ServerUrl表示请求服务器地址、ResourceUrl表示资源服务器地址、release表示是否为生产环境。

【HarmonyOS】【高级】关于鸿蒙原生项目多环境的配置和管理-鸿蒙开发者社区

{
  "ServerUrl": "https://www.dev.com/api/",
  "ResourceUrl": "https://www.dev.com/resource/",
  "release": false
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

4、配置工程支持多环境

  • 配置products

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

  • 配置modules

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

【HarmonyOS】【高级】关于鸿蒙原生项目多环境的配置和管理-鸿蒙开发者社区

{
  "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"
          ]
        }
      ]
    }
  ]
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78.
  • 79.
  • 80.
  • 81.
  • 82.
  • 83.
  • 84.
  • 85.
  • 86.
  • 87.
  • 88.
  • 89.
  • 90.
  • 91.
  • 92.
  • 93.
  • 94.
  • 95.
  • 96.
  • 97.

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

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

【HarmonyOS】【高级】关于鸿蒙原生项目多环境的配置和管理-鸿蒙开发者社区

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;
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.

6、生效当前环境信息

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

  • 创建HMAbilityStage.ets类,继承AbilityStage,重写onCreate()方法。
  • entry/src/main/module.json5文件中的配置srcEntry字段值为HMAbilityStage.ets文件的相对路径。

【HarmonyOS】【高级】关于鸿蒙原生项目多环境的配置和管理-鸿蒙开发者社区

{
  "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",
    // ...
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.

二、APP内动态切换环境

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

AppConfig.getInstance().init(getContext(this), 'app_config_test.json')
  • 1.

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

【HarmonyOS】【高级】关于鸿蒙原生项目多环境的配置和管理-鸿蒙开发者社区

结尾

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

©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
标签
已于2025-3-25 17:38:05修改
收藏
回复
举报


回复
    相关推荐
    这个用户很懒,还没有个人简介
    觉得TA不错?点个关注精彩不错过
    帖子
    视频
    声望
    粉丝
    社区精华内容