Mobile Development 19 min read

Mastering Hvigor: Build Tool Integration, Lifecycle, and Plugin Development for HarmonyOS

This article provides a comprehensive guide to the Hvigor build tool—its core features, integration with DevEco Studio, consistent build processes, lifecycle stages, typical usage scenarios, task and product structures, as well as step‑by‑step instructions for creating custom tasks, plugins, and routing plugins using TypeScript, enabling efficient and flexible development on HarmonyOS.

JD Cloud Developers
JD Cloud Developers
JD Cloud Developers
Mastering Hvigor: Build Tool Integration, Lifecycle, and Plugin Development for HarmonyOS

1. Overview of the Build Tool

Hvigor is a TypeScript‑based build orchestration tool designed to improve the efficiency of building and testing applications. Its key functions include:

Task management mechanism: registration and orchestration of build tasks.

Project model management: handling project structure and dependencies.

Configuration management: flexible options for custom configurations.

1. Integration of DevEco Studio with Hvigor

DevEco Studio uses Hvigor to automate and manage the build flow, producing HAP/APP packages. Advantages of Hvigor are its flexibility and independence:

Automated build process: Hvigor can automatically execute various build tasks within DevEco Studio, simplifying developers' workflow.

Independent execution: Hvigor can run inside DevEco Studio, via command‑line, or on CI servers, allowing use in any environment without IDE dependency.

2. Consistency of the Build Process

Whether using the command line or DevEco Studio, the build output remains consistent, ensuring identical results across environments and reducing environment‑related issues.

3. Typical Use Cases

Local development: developers can use Hvigor in DevEco Studio for rapid local development and testing.

Command‑line builds: Hvigor provides a CLI for terminal‑based task execution.

CI/CD: Hvigor can serve as the build tool on integration servers to automate build and test tasks, ensuring continuous integration and deployment.

Hvigor delivers an efficient, flexible build solution for developers, whether used inside DevEco Studio or via CLI and CI servers.

Supported Languages

Hvigor supports mainstream front‑end languages such as TypeScript and JavaScript.

2. Build Lifecycle

Before executing any task, Hvigor constructs a task dependency graph forming a directed acyclic graph (DAG).

Build lifecycle diagram
Build lifecycle diagram

The lifecycle consists of three stages: initialization, configuration, and execution, each with specific tasks and purposes.

1. Initialization

Purpose: initialize project compilation parameters and construct a tree‑structured data model of the project.

Steps:

Construct the tree model: each node becomes a HvigorNode object.

Set build parameters based on command‑line arguments and hvigor-config.json5.

Detect configuration files (e.g., build-profile.json5).

Create node descriptors from rootNodeDescriptor and module descriptors.

Execute the configuration file hvigorconfig.ts, registering hooks if needed.

Construct HvigorNode instances for each node.

2. Configuration

Purpose: load plugins, tasks, and the task dependency DAG for each node.

Load plugins and tasks by executing each node’s hvigorfile.ts, which registers plugins with Hvigor.

Apply each plugin’s apply method to add context.

Construct the DAG based on loaded plugins and task dependencies.

3. Execution

Purpose: execute selected tasks according to dependency order.

Determine task order from dependency relationships.

Execute tasks in parallel where possible to improve efficiency.

Through these three stages, Hvigor ensures an orderly, efficient build process with flexible configuration and extensibility.

Lifecycle Hook Points

Each stage provides multiple hook points (illustrated by the green‑outlined lines in the diagram).

Hook points diagram
Hook points diagram

3. Build Tasks and Artifacts

1. HAP Basic Task Flow

Run hvigorw taskTree to view tasks; the official documentation lists each task’s details. Currently, HarmonyOS does not support modifying task outputs.

2. HAP Build Artifacts

resources

: resource files such as images, media, and configuration files. modules.abc: compiled bytecode files. module.json: runtime configuration generated from module.json5. resources.index: resource index containing IDs, names, types, and values. pack.info: package description used during installation and upgrade.

4. Developing Custom Tasks

Edit hvigorfile.ts in the project and register tasks via the HvigorNode object:

// Get the current HvigorNode
const node = getNode(__filename);
// Register a task
node.registerTask({
  name: 'TaskName', // task name
  run() {
    // custom logic here
  }
});
// Execute the task
hvigorw TaskName

5. Developing Custom Plugins

For a simple plugin used in a single project, write it directly in hvigorfile.ts. For reusable plugins across multiple projects, extract it into a separate TypeScript project.

6. Example: Routing Plugin

// Define the plugin
function customPlugin(): HvigorPlugin {
  return {
    pluginId: 'customPlugin',
    apply(node: HvigorNode) {
      console.log('hello customPlugin!');
    }
  };
}
// Export the plugin in the project
export default {
  system: appTasks,
  plugins: [customPlugin()]
};
// Execute
hvigorw --sync

When using the Navigation system, a route table file route_map and page entry functions must be consistent. A custom plugin can automate this, though Huawei also provides the official HMRouter solution.

7. Abstract Syntax Tree (AST) Overview

An AST is a tree representation of source code structure, where each node corresponds to a syntactic construct.

let name = 'jd';
// AST representation (simplified)
File {
  type: File,
  start: 0,
  end: 18,
  program: Program {
    body: [
      VariableDeclaration {
        declarations: [
          VariableDeclarator {
            init: StringLiteral { value: 'jd' }
          }
        ],
        kind: 'let'
      }
    ]
  }
}

8. Development Steps for the Routing Plugin

Set up Node.js (v16‑v18) and add it to PATH.

Create an empty directory and navigate into it.

Install TypeScript globally: npm install typescript -g.

Initialize an npm project: npm init.

Generate a tsconfig.json: tsc --init.

Configure npm registry mirrors in .npmrc and add @ohos/hvigor as a devDependency.

Install dependencies: npm install.

9. Plugin Implementation Details

The plugin scans source files, analyzes decorators, and generates builder files, router maps, and index files. Key functions include: getAllFiles: recursively collect file paths. createBuilderFile, createRouterMapFile, createIndexFile: generate output files. initializeConfig: set up plugin configuration based on the Hvigor node. routerPlugin: entry point returning an HvigorPlugin object.

export function routerPlugin(pluginConfig?: RouterPluginConfig): HvigorPlugin {
  return {
    pluginId: PLUGIN_ID,
    apply(node: HvigorNode) {
      executePlugin(initializeConfig(node, pluginConfig));
    }
  };
}

10. Exporting the Plugin

export { routerPlugin } from './src/JRouterPlugin';

7. Conclusion

This article introduced the application of Hvigor in HarmonyOS, covering task and plugin development. By following the code examples and development ideas presented, readers can gain a deeper understanding of Hvigor and apply it effectively in their projects.

QR code for technical group
QR code for technical group
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

TypeScriptBuild ToolHarmonyOSPlugin DevelopmentHvigor
JD Cloud Developers
Written by

JD Cloud Developers

JD Cloud Developers (Developer of JD Technology) is a JD Technology Group platform offering technical sharing and communication for AI, cloud computing, IoT and related developers. It publishes JD product technical information, industry content, and tech event news. Embrace technology and partner with developers to envision the future.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.