Publish HarmonyOS Libraries to OpenHarmony: DevEcoCli & DevEcoCode Complete Workflow
This guide demonstrates the complete six-step workflow for developing and publishing HarmonyOS third-party libraries to the OpenHarmony central repository using DevEcoCli and DevEcoCode, covering account setup, RSA key configuration, HAR module creation, oh-package.json5 requirements, release-mode building, and ohpm publishing with troubleshooting tips.
Publishing a Third-Party Library to OpenHarmony Central Repository
The article outlines a standardized six-step process for publishing HarmonyOS third-party libraries (HAR packages) to the OpenHarmony central repository (https://ohpm.openharmony.cn/#/cn/home):
Account Registration — Register at the OpenHarmony central repository and complete real-name authentication.
Key Configuration — Generate RSA key pair in PEM format (password must be non-empty) and configure ohpm:
# 1. Generate RSA key pair (password must be non-empty)
ssh-keygen -m PEM -t RSA -b 4096 -f ~/ohpmkey
# 2. Configure private key path
ohpm config set key_path ~/ohpmkey
# 3. Configure publish_id (obtain from personal center)
ohpm config set publish_id UR7FAMETVUCopy the public key ( ohpmkey.pub) content to "Personal Center → Public Key Management".
Create Library Module — Use DevEco Studio: New → Module → Static Library or use devecocli to create a project and add a Library module.
Complete oh-package.json5 & Required Files — Module-level oh-package.json5 must include mandatory fields: name (with org prefix, e.g., @ericbyliang/lib_watermark), version (semver), main (entry file), license. All direct dependencies must be declared in this file; project-level config cannot fill gaps.
Note: The HAR module to be published must declare all its direct dependencies completely in its own oh-package.json5 ; project-level config cannot "fill gaps".
Three mandatory files must be present in the .har / .tgz package with non-empty, compliant content: LICENSE — Full license text, Apache-2.0 recommended. Quick generation:
curl https://www.apache.org/licenses/LICENSE-2.0.txt -o LICENSE readme.md— At least installation command and usage instructions changelog.md — At least version number and changes for that version
Build HAR — In DevEco Studio, select Library module → Build → Make Module . Output .har appears in build directory. Use release mode ; debug mode includes source code and risks leakage.
Publish & Review — Run ohpm publish lib_watermark.har (prompts for key password). After publishing, enters review; once approved, others install via ohpm install @ericbyliang/lib_watermark. Critical: Once a name+version combination passes review, it is permanently occupied (even if unpublished); version must be incremented for updates.
Common Issues Quick Reference
HttpCode 400 ... must contain a non-empty changelog.md — Missing or empty changelog.md; add it.
Public key verification failed — Key not PEM format RSA; regenerate with ssh-keygen -m PEM.
description / author rejected — Used default placeholder or empty; fill real content.
Name or version already exists — That name+version occupied; increment version and republish.
Install signature mismatch — Local cache issue; run ohpm install to force refresh.
DevEcoCode Practical Example: harmony-validator
Launch DevEcoCode with deveco, then describe requirements in natural language. Example prompt creates an ArkTS validation library ( harmony-validator) with static methods for phone, email, ID card (GB 11643-1999 checksum), URL, license plate (including new energy), strict mode (no any / as), regex constants in RegexKit.ets, JSDoc comments, Index.ets barrel export, and Hypium unit tests (≥3 cases per method). DevEcoCode outputs a plan; confirm to execute.
Generated Project Structure
HarmonyValidator/
├── library/ # HAR module root
│ ├── Index.ets # Unified entry (barrel export)
│ ├── oh-package.json5 # Module-level package description
│ ├── build-profile.json5 # Build config
│ └── src/main/
│ ├── module.json5 # Module manifest (type: har)
│ └── ets/
│ ├── RegexKit.ets # Shared regex constants
│ └── Validator.ets # Core validation logic
├── build-profile.json5 # Project-level build config
└── oh-package.json5 # Project-level package descriptionCore Files Explained
Index.ets — Barrel Entry
Entry point referenced by main in oh-package.json5. Re-exports internal implementations, shielding consumers from internal paths:
// Consumer writes only:
import { Validator } from "harmony-validator";Recommended practice for third-party libraries: internal directories can be refactored freely; as long as Index.ets exports remain stable, consumer code needs no changes.
RegexKit.ets — Centralized Regex Constants
All regex patterns defined as static readonly using new RegExp() (ArkTS strict mode forbids regex literals like /^1\d{10}$/):
export class RegexKit {
/** China mobile: starts with 1, second digit 3-9, 11 digits total */
static readonly PHONE: RegExp = new RegExp("^1[3-9]\\d{9}$");
/** Email */
static readonly EMAIL: RegExp = new RegExp(
"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$"
);
/** 18-digit ID card format (checksum validated by Validator) */
static readonly IDCARD: RegExp = new RegExp("^\\d{17}[\\dXx]$");
/** URL (http/https) */
static readonly URL: RegExp = new RegExp(
"^https?:\\/\\/[A-Za-z0-9.-]+(:\\d+)?...$"
);
/** License plate (incl. new energy) */
static readonly LICENSE_PLATE: RegExp = new RegExp("^[京津沪渝...][A-Z]...$");
}Key ArkTS constraint: Strict mode prohibits regex literals; all regex must be constructed via new RegExp('...') . DevEcoCode output complies automatically — a common pitfall when writing manually.
Validator.ets — Core Validation Logic
Pure logic class (no UI), all methods static. Most methods (phone, email, URL, license plate) check null then RegexKit.XXX.test(s). isIDCard implements GB 11643-1999 checksum algorithm:
static isIDCard(s: string): boolean {
// 1. Basic format: first 17 digits + last digit/X
if (!RegexKit.IDCARD.test(s)) return false
// 2. Weighted sum of first 17 digits
let sum: number = 0
for (let i = 0; i < 17; i++) {
const digit: number = s.charAt(i).charCodeAt(0) - '0'.charCodeAt(0)
sum += digit * ID_WEIGHTS[i] // ID_WEIGHTS = [7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2]
}
// 3. Mod 11, map to standard check code table
const expected: string = ID_CHECK_CODES[sum % 11] // ['1','0','X','9','8','7','6','5','4','3','2']
// 4. Compare with 18th character (case-insensitive X)
return expected === s.charAt(17).toUpperCase()
}A syntactically valid but fabricated ID (e.g., 110105194912310021) returns false due to checksum mismatch — impossible with regex alone.
oh-package.json5 — Package Metadata
Module-level config determines library identity in central repo. Initial DevEcoCode output had only five mandatory fields; after real publishing iteration, added homepage, repository, keywords, tags, bugs, ohos.org:
{
name: "harmony-validator",
version: "1.0.0",
description: "HarmonyOS ArkTS validation library: phone / email / ID card (GB11643 checksum) / URL / license plate (incl. new energy), pure logic no UI.",
main: "Index.ets",
author: "万少",
license: "Apache-2.0",
homepage: "https://github.com/itcastWsy/harmony-validator#readme",
repository: "https://github.com/itcastWsy/harmony-validator.git",
bugs: { url: "https://github.com/itcastWsy/harmony-validator/issues" },
keywords: [
"HarmonyOS", "OpenHarmony", "ArkTS", "validator", "validation",
"phone", "email", "idcard", "url", "license-plate"
],
tags: ["Tools"],
ohos: { org: "opensource" },
dependencies: {}
} main: "Index.ets"— Links barrel entry to package manager; consumer import { Validator } from 'harmony-validator' resolves to Index.ets. homepage / repository / bugs — Point to GitHub; shown on central repo detail page, aids issue reporting. keywords — Affects search relevance; cover platform + language + function. tags: ["Tools"] — Central repo category tag. ohos.org: "opensource" — Open-source library identifier.
Initial minimal config (name/version/main/author/license) passes review, but adding keywords and repository significantly improves discoverability and credibility.
Push Workflow
Ask DevEcoCode to verify publish readiness, supplement missing fields, then run:
ohpm publish library/build/default/outputs/default/library.harEnter private key password when prompted. On success, library enters review; central repo shows audit status.
Summary
Using harmony-validator as example, the article demonstrates the full zero-to-publish workflow for OpenHarmony third-party libraries.
Publishing Mainline (6 Standard Steps) — Mandatory path for all HarmonyOS third-party libraries:
① Register Org — Central repo real-name + create org. Pitfall: Package format @org/pkg; org name immutable.
② Configure Keys — RSA keypair + publish_id. Pitfall: Must be PEM format; password non-empty.
③ Create Library — DevEco Studio or devecocli. Pitfall: Choose Static Library (HAR).
④ Complete Config — oh-package.json5 + three files. Pitfall: LICENSE/readme/changelog — none missing.
⑤ Build HAR — Build → Make Module. Pitfall: Use release mode to prevent source leak.
⑥ Publish Review — ohpm publish. Pitfall: name+version permanently occupied.
DevEcoCode Development Mainline (Natural-Language Driven)
Requirements as Code: Describe validation rules, ArkTS strict constraints, test requirements in natural language; DevEcoCode generates structurally complete project (barrel entry, centralized regex, pure static methods, commented examples).
Constraints Built-In: DevEcoCode natively respects ArkTS strict mode (no regex literals, no any / as); generated code compiles and passes review without extra fixes.
Conversational Refinement: From minimal initial config to adding keywords / repository / tags, to pre-push compliance checks — all assisted via dialogue.
Two Engineering Practices to Remember
Barrel Entry ( Index.ets ): Unified re-export shields internal paths; future refactoring doesn't break consumers.
Centralized Regex ( RegexKit ): static readonly + new RegExp() satisfies ArkTS strict mode while enabling reuse and maintenance.
Third-party libraries are infrastructure of the HarmonyOS ecosystem. If you've encapsulated common utilities, UI components, or business SDKs in your projects, consider publishing them via this workflow — enables self-reuse and contributes to the community.
References
DevEco Studio Tools Overview: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/ide-tools-overview
DevEcoCode: HarmonyOS AI Agent: https://atomgit.com/openharmony-sig/deveco-code
@deveco/deveco-cli · npm: https://www.npmjs.com/package/@deveco/deveco-cli
HarmonyOS 7 New Features: https://developer.huawei.com/consumer/cn/features/?ha_source=51cto&ha_sourceId=70000008
HarmonyOS AI Dev Tools: DevEco Code & DevEco CLI: https://developer.huawei.com/consumer/cn/forum/topic/0202216647056043902?ha_source=51cto&ha_sourceId=70000008
Community Resources Collection: https://developer.huawei.com/consumer/cn/forum/topic/0201215860119833282?ha_source=51cto&ha_sourceId=70000008
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
51CTO HarmonyOS Developer Community
The HarmonyOS Developer Community is a learning-oriented community for developers to learn, communicate, ask questions, and share.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
