• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

How to Configure Multiple Environments for HarmonyOS Applications

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155
Preface


As we all know, development certificates and release certificates are not interchangeable. For those who have上架 (launched) apps before, it’s common knowledge that app submission rarely succeeds on the first try, and during daily updates, there are often scenarios where the app needs to be frequently launched or updated. However, each time you launch an app, you need to switch certificates and repackage the app.

But when there are many certificates, switching them becomes a tedious task. Forgetting to switch the correct certificate might lead to the app being rejected during submission, which is a minor issue. However, if it delays fixing a critical bug in the production environment, the consequences could be severe.

Additionally, when the environment changes, some variables (such as production server URLs) need to be adjusted accordingly. Forgetting to modify these variables can also cause significant problems.

Therefore, in development, there is a clear need to configure multiple sets of certificates and use environment variables for control.

Configure Multiple Environments


We need to configure app.products in the global build-profile.json5 to package multiple product variants. Example configuration:


"products": [
{
"name": "default", // Ensure at least one "default" product exists in products
"signingConfig": "default",
"compatibleSdkVersion": "5.0.0(12)",
"runtimeOS": "HarmonyOS",
"buildOption": {
"strictMode": {
"caseSensitiveCheck": true,
"useNormalizedOHMUrl": true
}
}
},
{
"name": "release",
"signingConfig": "release",
"compatibleSdkVersion": "5.0.0(12)",
"runtimeOS": "HarmonyOS",
"buildOption": {
"strictMode": {
"caseSensitiveCheck": true,
"useNormalizedOHMUrl": true
}
}
}
]

Add a new set of signatures named release (this name needs to correspond to the signingConfig above).


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.



Configure an additional target in the modules section to associate the phone entry with corresponding products:


{
"name": "phone",
"srcPath": "./entry",
"targets": [
{
"name": "default",
"applyToProducts": [
"default"
]
},
{
"name": "release",
"applyToProducts": [
"release"
]
}
]
}

Modify the targets configuration in build-profile.json5 under the entry directory:


[
{
"name": "default"
},
{
"name": "release"
}
]

This completes the configuration for multiple signing profiles. To switch between different signatures, simply click the Product icon in the top-right corner.


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.



Define Environment Variables


HarmonyOS projects are not frontend projects, so there is no .env file or --mode=production parameter.

We already know how to package multiple builds. Now, we just need to determine whether the current build is release or default to distinguish environments. Normally, we cannot directly know the current build mode, but the HAR runtime can obtain compilation parameters and generate a BuildProfile class file. Therefore, we can indirectly distinguish environments by introducing the BuildProfile file in the HAR package:


import BuildProfile from '../../../../BuildProfile';
const isRelease = (BuildProfile.BUILD_MODE_NAME as string) === 'release';

At this point, we can configure some JSON files and use the isRelease variable (or declare a mapping) to determine the current environment.

Summary


The general steps are as follows:

  1. Configure multiple sets of certificates and environment variables in HarmonyOS development.
  2. For multi-environment configuration, complete multiple signing configurations by editing the global build-profile.json5 and app.products, and switch signatures as needed.
  3. When defining environment variables, leverage the BuildProfile file introduced at HAR runtime to determine the build environment.

Article and code version: HarmonyOS 5.0.1 Release SDK.


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу