HarmonyOS鸿蒙Next中纯仓颉开发app,怎么读取配置信息

HarmonyOS鸿蒙Next中纯仓颉开发app,怎么读取配置信息 鸿蒙纯仓颉开发app,怎么读取配置信息,module.json5中的信息可以读取,但我想要配置一套代码生成多个项目,各个项目的配置信息不一样,但module.json5中好像只能配置一个项目的信息,build-profile.json5配置了多个,但是读取不到自己增加的信息,有没有其他办法实现运行一个项目读取对应的配置信息。

build-profile.json5
"products": [
  {
    "name": "default",
    "bundleName": "com.example.reportapp",
    //定义default的bundleName信息
    "signingConfig": "default",
    "targetSdkVersion": "5.0.5(17)",
    "compatibleSdkVersion": "5.0.5(17)",
    "runtimeOS": "HarmonyOS",
    "buildOption": {
      "strictMode": {
        "caseSensitiveCheck": true,
        "useNormalizedOHMUrl": true
      },
      "arkOptions": {
        "buildProfileFields": {
          "APP_CONFIG": "app_config_default.json",
          "productMessage": 'defaultMessage'
        }
      }
    }
  }

想要读取这个节点信息,代码中怎么写,后者其他思路也行。

“arkOptions”: { “buildProfileFields”: { “APP_CONFIG”: “app_config_default.json”, “productMessage”: ‘defaultMessage’ } }


更多关于HarmonyOS鸿蒙Next中纯仓颉开发app,怎么读取配置信息的实战教程也可以访问 https://www.itying.com/category-93-b0.html

6 回复

【背景知识】

自定义编译条件变量:仓颉支持通过预定义或自定义的条件完成条件编译。

【解决方案】

目前仓颉5.0.13.200 Canary版本的开发套件(配套DevEco Studio 5.0.5 Release)不支持直接获取build-profile.json5的配置信息,但是可以通过条件编译实现这样的效果。

例如在开发中,需要根据开发进展打包开发、测试、生产等不同服务器环境的APP,用仓颉的条件编译实现思路如下:

在项目的配置文件cjpm.toml中,在编译参数中增加自定义编译条件变量:

[target]
  [target.aarch64-linux-ohos]
    compile-option = "-B \"${DEVECO_CANGJIE_HOME}/compiler/third_party/llvm/bin\" -B \"${DEVECO_CANGJIE_HOME}/musl/usr/lib/aarch64-linux-ohos\" -L \"${DEVECO_CANGJIE_HOME}/musl/usr/lib/aarch64-linux-ohos\" -L \"${DEVECO_CANGJIE_HOME}/build/linux_ohos_aarch64_llvm/openssl\" --sysroot \"${DEVECO_CANGJIE_HOME}/musl\" --cfg=\"env=dev\""
    [target.aarch64-linux-ohos.bin-dependencies]
      path-option = [ "${AARCH64_LIBS}", "${AARCH64_MACRO_LIBS}" ]
      [target.aarch64-linux-ohos.bin-dependencies.package-option]

如上所示,在compile-option后面增加–cfg="env=dev"的编译参数,表示向编译器传递了一个值为dev的自定义编译条件变量env。

那么在代码中就可以通过判断该变量的值,来编译出不同环境的产物:

package ohos_app_cangjie_entry

internal import ohos.base.LengthProp
internal import ohos.component.Column
internal import ohos.component.Row
internal import ohos.component.Button
internal import ohos.component.Text
internal import ohos.component.CustomView
internal import ohos.component.CJEntry
internal import ohos.component.loadNativeView
internal import ohos.state_manage.SubscriberManager
internal import ohos.state_manage.ObservedProperty
internal import ohos.state_manage.LocalStorage
import ohos.state_macro_manage.Entry
import ohos.state_macro_manage.Component
import ohos.state_macro_manage.State
import ohos.state_macro_manage.r
import ohos.component.Web
import ohos.webview.WebviewController
import ohos.ark_interop.JSRuntime

// 如果编译条件变量env为test,就只编译如下函数
@When[env == "test"]
func initUrl() {
    return "env_test.example"
}

// 如果编译条件变量env为dev,就只编译如下函数
@When[env == 'dev']
func initUrl() {
    return "www.huawei.com"
}

@Entry
@Component
class EntryView {
    var testUrl: String = "";
    let controller: WebviewController = WebviewController();

    protected override func aboutToAppear() {
        this.testUrl = initUrl();
    }

    func build() {
        Row {
            Column {
                // 加载在线网页时需要申请ohos.permission.INTERNET权限
                Web(src: this.testUrl, controller: this.controller)
            }.width(100.percent)
        }.height(100.percent)
    }
}

更多关于HarmonyOS鸿蒙Next中纯仓颉开发app,怎么读取配置信息的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在鸿蒙纯仓颉开发中,若需通过一套代码实现多项目配置(如不同环境、产品变体),可通过以下方案实现:

一、核心思路

通过 构建时差异化配置 结合 动态资源加载 实现:

  • 构建阶段:利用 build-profile.json5 定义多个产品配置(products),注入差异化参数。
  • 运行阶段:通过资源文件或全局变量读取对应配置。

二、具体实现步骤

1. 配置多产品变体(build-profile.json5)

在 build-profile.json5 中定义不同产品的构建参数(如应用标识、API地址等):

// build-profile.json5(应用级)
{
  "app": {
    "products": [
      {
        "name": "product1",
        "signingConfig": "default",
        "buildParams": {  // 自定义字段
          "appId": "com.demo.product1",
          "apiBaseUrl": "https://api.product1.com"
        }
      },
      {
        "name": "product2",
        "signingConfig": "default",
        "buildParams": {
          "appId": "com.demo.product2",
          "apiBaseUrl": "https://api.product2.com"
        }
      }
    ]
  }
}

2. 生成动态配置文件

通过构建脚本(hvigorfile.ts)将产品配置注入到资源文件或全局变量:

// hvigorfile.ts(模块级)
import { task, ohos } from '@kit.BuildManagement';

task('generateConfig', () => {
  const productParams = ohos.build.product.buildParams; // 获取当前构建产品参数
  // 将参数写入资源文件(如config.json)
  fs.writeFileSync(
    'src/main/resources/base/element/config.json',
    JSON.stringify(productParams)
  );
});

// 绑定任务到构建流程
ohos.build.beforeAssembleTask('generateConfig');

3. 运行时读取配置

在仓颉代码中通过资源管理器加载配置:

// 示例代码(index.cj)
internal import ohos.resourceManager

// 读取配置
let resourceManager = ...; // 获取ResourceManager实例
let config = resourceManager.getStringByName('config'); // 从资源文件读取JSON字符串
let appConfig = JSON.parse(config);

// 使用配置
Text(appConfig.apiBaseUrl)
  .fontSize(16);

三、替代方案:条件编译

若需更精细化控制,可在构建时通过宏定义实现条件编译:

// hvigorfile.ts
ohos.build.product.flags = {
  "PRODUCT1": true,  // 根据当前产品设置标志
  "PRODUCT2": false
};

代码中通过条件判断:

// 仓颉代码
#if PRODUCT1
let apiUrl = "https://api.product1.com";
#elif PRODUCT2
let apiUrl = "https://api.product2.com";
#endif

四、注意事项

  1. 自定义字段合法性:build-profile.json5 中非标准字段需通过构建脚本处理,避免编译工具校验失败。
  2. 资源文件规范:自定义配置文件需放在 resources 目录,并通过标准资源访问接口读取。
  3. 多环境验证:确保不同产品构建产物独立签名、测试,避免配置污染。

五、总结

  • 推荐方案:优先采用 构建时注入资源文件 方式,符合鸿蒙资源管理规范且维护成本低。
  • 高级场景:若需动态切换环境(如测试/生产),可结合服务端配置下发实现。

感谢,我下来试试,非常感谢,

还没用过仓颉,关注,顶贴

在HarmonyOS Next中使用纯仓颉语言开发应用时,可通过@Config装饰器读取配置信息。首先在resources/base/profile/目录下创建JSON配置文件,定义所需配置项。在代码中导入配置模块,使用@Config装饰器声明配置变量并绑定配置路径,系统将自动注入配置值。例如:@Config('configFileName.key') private configValue: string。应用运行时可直接访问该变量获取配置数据。

在HarmonyOS Next纯仓颉开发中,可以通过以下方式读取build-profile.json5中的自定义配置信息:

  1. 使用系统提供的API获取构建配置字段:
import { buildProfile } from '@ohos/build-profile';

// 读取buildProfileFields中的配置
const appConfig = buildProfile.getBuildProfileField('APP_CONFIG');
const productMessage = buildProfile.getBuildProfileField('productMessage');
  1. 对于文件路径配置,可以结合资源管理器读取:
import { resourceManager } from '@ohos.resourceManager';

// 根据配置的文件路径读取对应配置文件
const configPath = buildProfile.getBuildProfileField('APP_CONFIG');
// 使用resourceManager读取配置文件内容
  1. 另一种实现思路是在代码中根据当前构建变体动态加载配置:
// 获取当前构建的产品名称
const currentProduct = buildProfile.getCurrentProduct();
// 根据产品名称加载对应的配置文件

这种方式可以实现一套代码根据不同的构建配置生成不同项目的应用,每个项目可以有自己的配置信息。

回到顶部