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

341 阅读4分钟

开发语言: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开发工具的工具条中,点击瞄准镜图标即可进行环境的切换。 image.png

2、配置签名(debug和release)

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

image.png

{
  "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
每个配置文件包含相同的三个字段:
ServerUrl表示请求服务器地址、ResourceUrl表示资源服务器地址、release表示是否为生产环境。

image.png

{
  "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中的各个环境。

image.png

{
  "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工程生成的编译文件,用来获取当前环境下的环境配置信息。

image.png

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文件的相对路径。

image.png

{
  "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')

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

sqbrg-55rie.gif

结尾

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