开发语言: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
字段的签名配置。
本文演示配置debug
和release
两个签名。
{
"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.json
、app_config_test.json
和app_config_release.json
。
每个配置文件包含相同的三个字段:
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')
示例中未进行数据持久化记录上次选中的环境,真正项目中可本地存储环境,下次启动使用切换后的环境配置信息
结尾
如大家发现文章描述有问题或有更好的方案,还请评论回复,一起探讨学习,感谢!