一、环境配置管理
- 配置文件分离
在工程
entry/src/main/resources/rawfile目录下创建环境专属配置文件(如app_config_dev.json、app_config_test.json),内容包含环境相关参数:
// app_config_dev.json
{
"ServerUrl": "https://dev.example.com",
"ResourceUrl": "https://res-dev.example.com",
"isProduction": false
}
通过build-profile.json5的arkOptions.buildProfileFields字段动态绑定环境配置:
// build-profile.json5
"products": [{
"name": "dev",
"arkOptions": {
"buildProfileFields": {
"APP_CONFIG": "app_config_dev.json"
}
}
}]
- 动态加载配置
通过
AppConfig.ets类读取当前环境配置:
// AppConfig.ets
import { BuildProfile } from '@kit.ArkUI.Core';
export class AppConfig {
static getConfig(): any {
const configName = BuildProfile.getBuildProfileField('APP_CONFIG');
return $rawfile(configName);
}
}
二、构建与部署自动化
- 多目标构建 使用Hvigor 插件实现环境差异化打包,动态注入环境参数(如 API 地址、埋点配置):
// hvigorfile.ts
const envParams = {
dev: { clientId: "dev_123", apiBase: "https://dev.api.com" },
prod: { clientId: "prod_456", apiBase: "https://api.com" }
};
- 原子化服务隔离
通过 AGC 平台为不同环境分发独立的
.hap包,确保测试/预发/生产环境数据隔离。配置沙箱环境时,修改module.json5中的distroFilter字段:
"distroFilter": {
"apiVersion": 5,
"environment": "test" // 指定环境类型
}
三、环境切换与调试
- 开发工具支持
在 DevEco Studio 工具条点击环境切换图标,快速切换开发/测试/生产环境配置。结合
@ohos.app.context获取运行时环境标识:
import { context } from '@kit.AbilityKit';
const currentEnv = context.getApplicationContext().config.environment;
- 安全管控
禁止使用动态代码注入(如
eval),通过静态类型校验确保环境参数安全性。使用环境变量替代硬编码敏感信息:
const apiKey = process.env.API_KEY; // 通过构建脚本注入
四、测试环境隔离
- 自动化测试包构建
使用DevEco Testing Hypium框架为每个环境生成独立测试包,通过
Example.json配置设备类型和执行策略:
{
"targetDevice": ["phone", "tablet"],
"env": "test",
"retryCount": 2
}
- 资源隔离
不同环境使用独立的资源目录(如
resources-test/images),通过条件编译控制资源加载:
#if ENV == 'test'
Image($r('app.media.test_logo'))
#else
Image($r('app.media.prod_logo'))
#endif
最佳实践
- 统一 SDK 版本:强制对齐
compileSdkVersion和compatibleSdkVersion,避免环境差异导致 API 不兼容。 - Git 流程管控:通过预提交钩子(Pre-commit Hook)自动执行环境配置校验,防止错误配置进入代码库。
- 性能监控:在测试环境中集成ArkTS Linter检查资源泄露和类型错误,阻断不符合生产标准的代码提交。
通过上述方案,可实现开发→测试→预发→生产环境的全链路隔离,华为公开数据显示该模式可减少**30%**的配置错误率。