背景: 一般一个公司的项目,先是在开发环境上联调测试好之后,会在仿真模拟环境上再进行验证,最后是联调通过后在生产环境上打包发布。所以,APP开发需要同时打出三种环境的包:开发环境包,仿真环境包,测试环境包。鸿蒙APP开发也不例外
1.分层级配置接口地址,从工程级目录build-profile.json5中读取,类似于安卓的BuildConfig文件
- APP中接口请求通用逻辑,比如接口前缀,环境声明,是否为调试模式,是否打印网络请求日志等
import BuildProfile from 'BuildProfile'
enum EnvType {
PRODUCT,FANGZHEN,DEBUG
}
export class UrlCommonConfig{
protected static envType:EnvType = EnvType.PRODUCT
protected static URL_API_HOME:string = BuildProfile.URL_API_HOME
protected static getHomeUrl():string{
return UrlCommonConfig.URL_API_HOME;
}
}
- 子模块继承UrlCommonConfig,申明属于自身模块的Url配置
import BuildProfile from 'BuildProfile'
import { UrlCommonConfig } from '../common/UrlCommonConfig';
enum EnvType {
PRODUCT,FANGZHEN,DEBUG
}
export class UrlNewsConfig extends UrlCommonConfig{
protected static NEWS_DETAIL:string = BuildProfile.NEWS_DETAIL
protected static NEW_RECOMMEND:string = `${this.getHomeUrl()}/getRecommend`
protected static getNewsDetailUrl():string{
return UrlNewsConfig.NEWS_DETAIL;
}
protected static getNewsRecommendUrl():string{
return UrlNewsConfig.NEW_RECOMMEND;
}
}
2.修改配置文件,配置不同环境的产物
- 修改entry模块中配置build-profile.json5
"targets": [
{
"name": "default"
},
{
"name": "ohosTest",
},
{
"name": "fangzhen",
},
{
"name": "debug",
}
]
- 修改工程级目录build-profile.json5
"products": [
{
"name": "default",
"signingConfig": "default",
"compatibleSdkVersion": "5.0.0(12)",
"runtimeOS": "HarmonyOS",
"buildOption": {
"arkOptions": {
"buildProfileFields": {
"NEWS_DETAIL": 'https://www.xxx.com:8888/news/#/flashnew?type=8',
"URL_API_HOME": 'https://www.xxx.com:8888'
}
}
}
},
{
"name": "fangzhen",
"signingConfig": "default",
"compatibleSdkVersion": "5.0.0(12)",
"runtimeOS": "HarmonyOS",
"buildOption": {
"arkOptions": {
"buildProfileFields": {
"NEWS_DETAIL": 'https://101.20.30:8888/news/#/flashnew?type=8',
"URL_API_HOME": 'https://101.20.30:2022'
}
}
}
},
{
"name": "debug",
"signingConfig": "default",
"compatibleSdkVersion": "5.0.0(12)",
"runtimeOS": "HarmonyOS",
"buildOption": {
"arkOptions": {
"buildProfileFields": {
"NEWS_DETAIL": 'https://192.168.30:8888/news/#/flashnew?type=8',
"URL_API_HOME": 'https://192.168.30.com:8888'
}
}
}
}
],
"buildModeSet": [
{
"name": "debug",
},
{
"name": "release"
}
]
},
"modules": [
{
"name": "entry",
"srcPath": "./entry",
"targets": [
{
"name": "default",
"applyToProducts": [
"default"
]
},
{
"name": "fangzhen",
"applyToProducts": [
"fangzhen"
]
},
{
"name": "debug",
"applyToProducts": [
"debug"
]
}
]
}
]
3.打包的时候需要选择对应的环境,apply后,点击三角形运行,就可以生成对应的包
*Build Mode/module Target可以选择release 或debug