鸿蒙中 自定义构建参数

本文同步发表于我的微信公众号,微信搜索 程语新视界 即可关注,每个工作日都有文章更新

一、自定义构建参数

自定义构建参数 是 HarmonyOS 开发中一个重要的功能,允许在编译构建过程中定义和使用自定义参数。通过 Hvigor 构建系统,可以在运行时获取构建相关的信息,包括系统默认参数和用户自定义参数。

核心

  • 构建时信息传递:将构建时的配置信息传递到运行时代码中

  • 环境差异化配置:根据不同构建模式(debug/release)使用不同参数

  • 模块间配置共享:在 HAP、HSP、HAR 中统一管理构建参数

二、HAP/HSP 构建参数使用

1. 生成 BuildProfile 类文件

生成方式
  • 菜单操作Build > Generate Build Profile ${moduleName}

  • 构建操作Build > Build Hap(s)/APP(s) > Build Hap(s)

  • 命令行hvigorw GenerateBuildProfile

生成路径
${moduleName}/build/${productName}/generated/profile/${targetName}/BuildProfile.ets

2. 代码中使用构建参数

导入方式
// packageName 对应模块级 oh-package.json5 中的 name 字段
import BuildProfile from '${packageName}/BuildProfile';
推荐用法(避免跨包集成问题)
// 推荐:使用完整包名导入
import BuildProfile from 'com.example.myapp/BuildProfile';

// 不推荐:在 HSP 中可能产生编译错误
import BuildProfile from 'BuildProfile';
在代码中获取参数
@State appBundleName: string = BuildProfile.BUNDLE_NAME;
@State isDebugMode: boolean = BuildProfile.DEBUG;

3. 默认参数列表

参数名类型说明
BUNDLE_NAMEstring应用的 Bundle 名称
BUNDLE_TYPEstring应用的 Bundle 类型
VERSION_CODEnumber应用的版本号
VERSION_NAMEstring应用版本号的文字描述
TARGET_NAMEstringTarget 名称
PRODUCT_NAMEstringProduct 名称
BUILD_MODE_NAMEstring编译模式
DEBUGboolean应用是否可调试

4. 自定义参数配置

配置位置

在模块级 build-profile.json5 中的以下节点配置:

  • buildOption

  • buildOptionSet

  • targets

配置示例
{
  "apiType": "stageModel",
  "buildOption": {
    "arkOptions": {
      "buildProfileFields": {
        "apiBaseUrl": "https://api.staging.com",
        "featureToggle": true,
        "maxRetryCount": 3
      }
    }
  },
  "buildOptionSet": [
    {
      "name": "release",
      "arkOptions": {
        "buildProfileFields": {
          "apiBaseUrl": "https://api.production.com",
          "enableAnalytics": true,
          "logLevel": "error"
        }
      }
    },
    {
      "name": "debug", 
      "arkOptions": {
        "buildProfileFields": {
          "apiBaseUrl": "https://api.dev.com",
          "enableAnalytics": false,
          "logLevel": "debug"
        }
      }
    }
  ],
  "targets": [
    {
      "name": "phone",
      "config": {
        "buildOption": {
          "arkOptions": {
            "buildProfileFields": {
              "deviceType": "phone",
              "screenDensity": "hdpi"
            }
          }
        }
      }
    },
    {
      "name": "tablet",
      "config": {
        "buildOption": {
          "arkOptions": {
            "buildProfileFields": {
              "deviceType": "tablet", 
              "screenDensity": "xhdpi"
            }
          }
        }
      }
    }
  ]
}
参数类型限制
  • 支持numberstringboolean

  • 不支持:对象、数组、函数等复杂类型

三、HAR 构建参数使用

1. 生成 BuildProfile 类文件

生成方式
  • 菜单操作Build > Generate Build Profile ${moduleName}

  • 菜单操作Build > Make Module ${moduleName}

  • 命令行hvigorw GenerateBuildProfile

生成路径
模块根目录/BuildProfile.ets

建议:将该文件添加到 .gitignore 中忽略版本控制

2. 代码中使用构建参数

导入方式
// 使用相对路径导入
import BuildProfile from './BuildProfile';
使用示例
// 在 HAR 的 Index.ets 或其他文件中使用
export const libraryVersion: string = BuildProfile.HAR_VERSION;
export const isDebugBuild: boolean = BuildProfile.DEBUG;

export class NetworkUtils {
  static getBaseUrl(): string {
    if (BuildProfile.DEBUG) {
      return "https://test.api.com";
    }
    return "https://api.com";
  }
}

3. 默认参数列表

参数名类型说明
HAR_VERSIONstringHAR 版本号
BUILD_MODE_NAMEstring编译模式
DEBUGboolean是否可调试
TARGET_NAMEstring目标名称

4. 自定义参数配置

配置位置

在 HAR 模块的 build-profile.json5 中配置:

  • buildOption

  • buildOptionSet

配置示例
{
  "apiType": "stageModel", 
  "buildOption": {
    "arkOptions": {
      "buildProfileFields": {
        "libraryName": "NetworkLibrary",
        "timeoutMs": 5000
      }
    }
  },
  "buildOptionSet": [
    {
      "name": "release",
      "arkOptions": {
        "buildProfileFields": {
          "enableDetailedLogs": false,
          "cacheSize": "100MB"
        }
      }
    },
    {
      "name": "debug",
      "arkOptions": {
        "buildProfileFields": {
          "enableDetailedLogs": true,
          "cacheSize": "50MB"
        }
      }
    }
  ]
}

四、工程级构建参数配置

配置位置

在工程级 build-profile.json5 中配置:

  • products

  • buildModeSet

配置示例

{
  "app": {
    "signingConfigs": [],
    "products": [
      {
        "name": "production",
        "signingConfig": "release",
        "compatibleSdkVersion": "10.0.0(API 10)",
        "runtimeOS": "HarmonyOS",
        "buildOption": {
          "arkOptions": {
            "buildProfileFields": {
              "environment": "production",
              "supportEmail": "support@company.com"
            }
          }
        }
      },
      {
        "name": "staging", 
        "signingConfig": "debug",
        "compatibleSdkVersion": "10.0.0(API 10)",
        "runtimeOS": "HarmonyOS", 
        "buildOption": {
          "arkOptions": {
            "buildProfileFields": {
              "environment": "staging",
              "supportEmail": "staging-support@company.com"
            }
          }
        }
      }
    ],
    "buildModeSet": [
      {
        "name": "debug",
        "buildOption": {
          "arkOptions": {
            "buildProfileFields": {
              "enableDebugTools": true,
              "mockServerEnabled": true
            }
          }
        }
      },
      {
        "name": "release",
        "buildOption": {
          "arkOptions": {
            "buildProfileFields": {
              "enableDebugTools": false,
              "mockServerEnabled": false
            }
          }
        }
      }
    ]
  },
  "modules": [
    {
      "name": "entry",
      "srcPath": "./entry",
      "targets": [
        {
          "name": "default",
          "applyToProducts": ["production", "staging"]
        }
      ]
    }
  ]
}

作用范围

工程级配置的自定义参数会生成到所有模块的 BuildProfile 类文件中,实现全局统一配置。

五、优先级规则

配置优先级(从高到低)

模块级 targets → 模块级 buildOptionSet → 模块级 buildOption → 工程级 products → 工程级 buildModeSet

优先级示例

// 假设有以下配置,最终生效的值:
{
  "buildOption": {
    "arkOptions": {
      "buildProfileFields": {
        "apiUrl": "https://default.api.com"  // 最低优先级
      }
    }
  },
  "buildOptionSet": [
    {
      "name": "debug", 
      "arkOptions": {
        "buildProfileFields": {
          "apiUrl": "https://debug.api.com"  // 中等优先级
        }
      }
    }
  ],
  "targets": [
    {
      "name": "phone",
      "config": {
        "buildOption": {
          "arkOptions": {
            "buildProfileFields": {
              "apiUrl": "https://phone.api.com"  // 最高优先级
            }
          }
        }
      }
    }
  ]
}

六、应用示例

1. 环境差异化配置

// 根据构建模式配置不同的 API 地址
class AppConfig {
  static getApiBaseUrl(): string {
    if (BuildProfile.DEBUG) {
      return BuildProfile.debugApiUrl || "https://dev.api.com";
    }
    return BuildProfile.releaseApiUrl || "https://api.com";
  }
  
  static isFeatureEnabled(featureName: string): boolean {
    return BuildProfile[`feature_${featureName}`] === true;
  }
}

2. 构建信息展示

@Entry
@Component
struct AboutPage {
  build() {
    Column() {
      Text(`应用版本: ${BuildProfile.VERSION_NAME}`)
        .fontSize(18)
      Text(`构建模式: ${BuildProfile.BUILD_MODE_NAME}`)
        .fontSize(16)
      Text(`Bundle名称: ${BuildProfile.BUNDLE_NAME}`)
        .fontSize(16)
    }
  }
}

3. 库版本管理

// 在 HAR 中管理版本信息
export class UtilsLibrary {
  static getVersionInfo(): string {
    return `UtilsLibrary v${BuildProfile.HAR_VERSION} (${BuildProfile.BUILD_MODE_NAME})`;
  }
}

七、建议

1. 命名规范

  • 使用驼峰命名法apiBaseUrlenableFeatureX

  • 避免使用保留字特殊字符

  • 保持命名语义清晰

2. 类型安全

// 为自定义参数创建类型定义
interface CustomBuildProfile {
  apiBaseUrl?: string;
  enableExperimental?: boolean;
  maxCacheSize?: number;
}

// 使用类型断言
const customProfile = BuildProfile as typeof BuildProfile & CustomBuildProfile;
const apiUrl = customProfile.apiBaseUrl;

3. 错误处理

class BuildConfig {
  static getValue<T>(key: string, defaultValue: T): T {
    try {
      const value = BuildProfile[key];
      return value !== undefined ? value : defaultValue;
    } catch (error) {
      console.warn(`Build parameter ${key} not found, using default`);
      return defaultValue;
    }
  }
}

// 使用
const apiTimeout = BuildConfig.getValue<number>('apiTimeout', 30000);

八、注意事项

  1. 文件生成时机:BuildProfile 文件在特定构建操作时生成,非实时更新

  2. 版本控制:建议将生成的 BuildProfile 文件添加到 .gitignore

  3. 跨包引用:HSP 中避免使用相对路径导入

  4. 类型限制:只支持基本数据类型,不支持复杂对象

  5. 优先级理解:了解各配置位置的优先级,避免意外覆盖

   通过使用自定义构建参数,可以实现灵活的构建时配置,满足不同环境、不同设备的差异化需求,提升开发效率和应用的适应性。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值