跪拜 Guibai
← Back to the summary

Vite Build Outputs, Reborn as HAP, HAR, HSP on HarmonyOS

Web to HarmonyOS - Packaging: Vite artifacts → HAP / HAR / HSP

Series: "Web to HarmonyOS" · Part 10
Audience: those who know Vue3 + Vite, understand dist, route lazy-loading and manualChunks, and are ready to understand what HarmonyOS apps eventually package into


Preface

In a Vue project, after npm run build you get dist: an entry page, several js files split by route, and sometimes a chunk for common dependencies. HarmonyOS does the same thing before publishing, but the outputs are renamed HAP, HAR, HSP, and finally wrapped into one .app.

What can be installed on a phone and entered by tapping an icon is HAP. What gets compiled into each consumer at build time, leaving a copy in each one, is HAR. What compiles into its own standalone file and exists only once across the whole app at runtime is HSP.

What you've seen in Vue / Vite HarmonyOS artifact What it actually does
Site entry index.html + main bundle entry-type HAP (.hap) App entry. Only one entry per device type
An entire installable business block, not just a lazy-loaded route feature-type HAP Dynamic feature module, can be installed separately, still belongs to this app
Internal component library bundled into every app HAR (.har) Reusable at compile time. Use once, copy once
Shared chunk from manualChunks / splitVendorChunk HSP (.hsp) Reusable at runtime. Only one copy on disk and in the process
A private package integrated into multiple apps, runtime identity must match host Integration-state HSP No bundleName at publish time; replaced with the host's bundleName and re-signed when integrated
The whole site Bundle All HAPs and HSPs in one app. bundleName is the unique identifier
The package you hand to the publishing system App Pack (.app) The basic unit for listing
manifest.json / build manifest pack.info Records each HAP's and HSP's name, type, Ability
package.json oh-package.json5 Declares dependencies
exports in package.json, barrel file index.ts index.ets at module root Only things re-exported from here are accessible outside
npm OHPM HAR can be published here for other apps

Signatures are applied separately for HAP, HSP, and APP. Cloud distribution and phone-side installation work with HAP and HSP files. When listing, you submit a .app; when installing on a device, the system extracts and installs the individual .hap and .hsp files inside.

This repository is still a single entry. Below, I first align with the existing project, then explain how to connect things when you need to split out a shared module. For the overall module and route diagram, see 02-ability-stage-module-router.md.


1. This repository is currently one entry package

AppScope/app.json5 is the app identity, equivalent to a site's origin: package name, version, icon, name.

{
  "app": {
    "bundleName": "com.example.myapplication",
    "vendor": "example",
    "versionCode": 1000000,
    "versionName": "1.0.0",
    "icon": "$media:layered_image",
    "label": "$string:app_name"
  }
}

The type of entry is entry, and the Ability that the desktop taps into is recorded in mainElement. This is the single index.html in a Vue project.

{
  "module": {
    "name": "entry",
    "type": "entry",
    "description": "$string:module_desc",
    "mainElement": "EntryAbility",
    "deviceTypes": [
      "phone"
    ],
    "deliveryWithInstall": true,
    "installationFree": false,

The modules in the project-level build-profile.json5 currently contains only entry. Neither the root nor the entry oh-package.json5 has business dependencies. That means: no HAR, no HSP, the output is a single HAP, then wrapped into a .app.

Dependencies are written in the module's oh-package.json5 in the future, just like a Vue sub-package has its own package.json; don't write them at the wrong layer. The official requirement also says: when using overrides to pin versions, it must be written at the project root oh-package.json5; writing it at module level won't take effect.


2. HAP: the layer that runs

HAP stands for Harmony Ability Package. A .hap contains code, resources, third-party libraries, and configuration. It is the basic unit for installation and running. An app has at least one HAP.

Two types:

Type type in module.json5 Vue analogy Constraints
entry entry Main app. User taps icon to enter Only one entry per device type. The entry Ability's skills carries entity.system.home and ohos.want.action.home
feature feature A business block that can be installed later Can have multiple, or none. Can be installed separately, still belongs to this bundleName

This is distinct from Vue's route lazy-loading.

() => import('./views/Vip.vue') still lives in the same dist, just as another js file. It's closer to a dynamic import inside the same HAP, not a feature.

A feature is a functional module that the app market can install later. The user's first download may not include it; it gets installed when used. The official name for this is on-demand distribution. That's about "whether this feature gets downloaded", which is a different question from the next section's "whether this code gets copied once in each package".


3. HAR: the component library consumed at compile time

HAR stands for Harmony Archive, a static shared package with the .har suffix. It can contain ArkTS, C++ .so files, resources, and configuration. It can be shared within the project, or published to OHPM. It cannot be installed on a phone by itself.

Vue comparison: in a monorepo, a packages/ui is depended on by both apps/main and apps/admin. Vite bundles that package into each app's output. You won't see the packages/ui directory in the deployed site; you only see its code in each bundle. HAR works the same way.

When a HAP or HSP is compiled, the HARs it depends on get compiled directly into it. So if you unpack the final .app, you only see .hap and .hsp; you never see .har. In the consuming module's compiled module.json, dependencies will show HSP module names but not HARs – by that point the HAR has become part of the consumer's bytecode. The ets source gets compiled to .abc at this step.

Each consumer carrying its own copy is the reason packages get bigger. If two entries both import the same large component library and no shared chunk is extracted, dist contains two copies. HAR's multi-package reference produces the same result.

In a single-HAP project this is usually not a problem: there's only one consumer and the copy happens once. This repository is currently like that. Putting common components, utility functions, and models into a HAR first is enough.


4. HSP: only one copy at runtime

HSP stands for Harmony Shared Package, a dynamic shared package with the .hsp suffix. Content mirrors HAR – it can have code, .so, resources, configuration – but it is compiled independently. If multiple HAPs reference it, the .app contains only this one copy; the process also has only one copy.

Vite analogy: when two entries depend on the same large piece of business code, use build.rollupOptions.output.manualChunks to extract it into a separate chunk, and have both entries reference that chunk. HSP is exactly that shared chunk, and the system guarantees it loads only once at runtime. The documentation also notes: HSP is loaded on demand at runtime.

It travels with the host app, with three boundaries where Vue experience doesn't map.

Bound to the host. An in-app HSP cannot be listed on its own. It ships with the host .app, runs in the same process, same bundleName, and same lifecycle as the host. It is coupled to that package name at compile time and can only be used by that one app.

To share across multiple apps, use integration-state HSP. It's an intermediate product of an in-app HSP. During build and publish it isn't welded to a specific package name; when used, the toolchain swaps in the host's bundleName, re-signs, and the resulting new HSP is the host's own installable package. Suitable for sharing code and resources across multiple apps in one organization.

Dependencies don't propagate, and no cycles. An HSP can depend on other HARs or HSPs, and can be depended on by HAPs or HSPs. When A depends on B and B on C, A cannot directly use C's methods or components. With npm, hoisting sometimes lets you "accidentally" reference C; here, that's not possible. Cycles like A → B → C → A are also disallowed.

Since API 14, an HSP may declare UIAbility in its configuration, but it cannot be a desktop entry (cannot configure entity.system.home + ohos.want.action.home). Since API 18, it can declare ExtensionAbility, likewise not as an entry.


5. From source code to listing

Development, compilation, and publishing are three forms.

flowchart LR
  subgraph dev [Development state]
    src[entry's ets]
    harSrc[HAR module]
    hspSrc[HSP module]
  end
  subgraph build [Compilation state]
    hap[entry.hap / feature.hap]
    hspFile[library.hsp]
  end
  subgraph ship [Publishing state]
    app["App Pack .app"]
    info[pack.info]
  end
  src --> hap
  harSrc --> hap
  harSrc --> hspFile
  hspSrc --> hspFile
  hap --> app
  hspFile --> app
  app --> info

The development state is the project directory, corresponding to a Vue repo:

HarmonyOS Vue project
AppScope/app.json5 App name, version, icon. There's no browser layer; the package name is written here
module/src/main/module.json5 Whether this package is entry, feature, or shared, plus Ability, permissions, pages
module/src/main/ets Scripts in src/**/*.vue. ArkUI has no separate .vue template files
AppScope/resources, module/src/main/resources public/ and each package's own static resources
oh-package.json5 dependencies in package.json
build-profile.json5, hvigorfile.ts vite.config.ts. Signing, products, build modes are written here

At compile time, two merges also happen: AppScope/resources gets merged into module resources, and when names collide the app-level copy wins; app.json5 gets merged into the module configuration to produce the final module.json.

The publishing state collects all .hap and .hsp into a Bundle, then packages it as a .app. DevEco Studio simultaneously generates pack.info, recording bundleName, versionCode, and each module's name, type, and abilities. .hsp is optional. This repository is currently "one entry HAP + one .app".


6. After multiple packages, where does copying happen

When multiple HAPs directly depend on the same set of HARs, each HAP recompiles those HARs into itself. The official example: HAP1, and HAP2 (or another HSP1), both reference HAR2 and HAR3. After packaging, HAR2 and HAR3 each have multiple copies.

Put HAR2 and HAR3 into a single HSP2, and let HAP1, HAP2 depend only on HSP2. HARs are still compiled into their consumers, but now the only consumer is HSP2, so those two HARs appear only once in the whole .app. When HAR2 + HAR3's size exceeds HSP's own overhead, the package gets smaller.

flowchart TB
  subgraph copies [Multiple HAPs directly depend on HAR]
    HAP1 --> HAR2
    HAP1 --> HAR3
    HAP2 --> HAR2b[Another copy of HAR2]
    HAP2 --> HAR3b[Another copy of HAR3]
  end
  subgraph once [Changed to one HSP carrying them]
    HAP1b[HAP1] --> HSP2
    HAP2b[HAP2] --> HSP2
    HSP2 --> onceHar[HAR2 and HAR3 compiled into HSP2 only once]
  end

This is the same cost calculus as two Vite entries each bundling a large dependency, then extracting a shared chunk.

The documentation also warns against the opposite: heavily replacing HARs with HSPs raises compile time and memory. Modules referencing those HSPs trigger more language compilation tasks during compile. Keep small components and utility functions in HARs.


7. Adding an HSP is like adding a workspace package

This repository does not yet have a library module. Below is the official way to split out a shared capability into its own module, with the files you'd write. Dependency sources use file:, playing the same role as pnpm workspace's workspace:*.

In an HSP's module.json5, type is shared. Only the root-level index.ets is visible externally; anything not exported from there cannot be referenced by consumers. That's the exports equivalent.

// library/src/main/ets/utils/Calc.ets
export class Calc {
  static add(a: number, b: number): number {
    return a + b;
  }
}
// library/index.ets
export { Calc } from './src/main/ets/utils/Calc';
// entry/oh-package.json5
{
  "name": "entry",
  "dependencies": {
    "library": "file:../library"
  }
}
// entry/src/main/ets/pages/Index.ets
import { Calc } from 'library';

@Entry
@Component
struct Index {
  @State result: number = 0;

  build() {
    Column() {
      Text(`Calculation result: ${this.result}`)
      Button('Call HSP')
        .onClick(() => {
          this.result = Calc.add(1, 2);
        })
    }
  }
}

When depending on an already-built artifact: use .har for HAR, and for HSP use the release .tgz, written as "library": "file:../library.tgz", then run ohpm install. Once configured, the call pattern is the same as HAR.

Don't use relative path strings for resources. Writing Image("../../resources/base/media/example.png") inside an HSP will actually look in the caller's (e.g., entry's) resource directory. In Vite, a relative path is relative to the file writing it; here, that string falls through to the caller. Use $r('app.media.example') for the HSP's own resources. For images and text meant to be used externally, wrap them in a manager class and export from index.ets, so internal renames don't force consumers to change.

To navigate from an entry to a page inside an HSP, use Navigation's route table and add a routerMap to the HSP's module.json5. The distinction between a whole-page entry and a drill-down inside a Tab still follows Part 2: use router for an entire page change, and Navigation for drilling down within the current business flow.


8. How to choose

Scenario Use What you'd probably already do in Vue
One HAP, reusing components and utility functions HAR In a single-page app, extract components/ and utils/, bundle them into one bundle
Multiple HAPs sharing a large business block, resources, and .so HSP In a multi-entry project, extract large dependencies as a shared chunk
A library exposed to other apps HAR, publish to OHPM npm publish a component library
Multiple apps in the same organization sharing Integration-state HSP Private package, upon integration replace with host package name and re-sign
Infrequently used whole block, wanting users to download it on demand feature-type HAP Standalone sub-app, installed after the main package. Not route lazy-loading

If the next step for this repository is just extracting common UI out of entry, use HAR. When a second HAP actually appears and both need to carry the same large business code, pull that block into an HSP.

Mnemonic: reuse within one entry uses HAR; large shared blocks across multiple installable packages use HSP; features that need separate download use feature HAP.

Comments

Top 1 from juejin.cn, machine-translated. The original thread is authoritative.

组合搭配函数

This splitting approach is quite clear. Single-package only uses HAP, multi-package splits by business, when to extract HAR and when to extract HSP, it all clicks right away. Extracting common UI for reuse is quite practical.