目录

Customizing the Hvigor Plugin

Overview

During compilation and build, you can customize the Hvigor plugin to extend the build logic and implement personalized packaging.

The purposes of customizing the Hvigor plugin are as follows:

In specific application scenarios, the custom plugin can adjust compilation output attributes based on different build requirements to manage the build flexibly.

The following uses the file name and path of the custom build output as an example to describe how to customize the Hvigor plugin.

[h2]Basic Concepts

The following concepts are involved in the development of the custom Hvigor plugin:

Implementation Principles

The custom Hvigor plugin is used to insert required custom tasks during compilation and build, abstract and encapsulate these custom tasks into reusable parts, and output the plugin target, thereby implementing reuse, sharing, and distribution of personalized compilation and build logic.

As shown in the preceding figure, the working principle of the Hvigor plugin is as follows:

  1. Developers create a custom plugin, customize tasks in the plugin, and apply the plugin in the project build script.
  2. hvigor-ohos-plugin installs the default build tasks and custom plugin tasks into the Hvigor task flow.
  3. Hvigor checks the nodes during the sequential execution of the Hvigor task flow, and executes the corresponding custom task logic when a custom task is registered.

[h2]Development Process

Hvigor provides two plugin development modes:

The two modes have similar core logic implementations, that is, creating tasks in a TypeScript file, but differ in sharing and application.

The comparison is as follows:

Table 1 Comparison between the two modes of customizing the Hvigor plugin
  

Plugin Project

Code Development

Sharing Method

Plugin Usage

Features

Based on the hvigorfile script

No project is created.

Directly edit the hvigorfile.ts file in the project or module.

The plugin is not released, and the code can be copied for sharing.

Directly apply the code logic to the edited project/module.

Quick development and use; inconvenient sharing and reuse.

Based on a TypeScript project

An npm project is created.

Create the custom-plugin.ts file.

The plugin is packed into an npm package for release and sharing, or packed into an offline package for sharing.

Configure the plugin dependencies in hvigor-config.json5 or install the offline package.

Easy to distribute, share, and maintain; more complex release and use processes.

The following uses developing a plugin based on a TypeScript project as an example. You can also directly write the plugin logic code in the hvigorfile.ts file and switch to developing a plugin with the hvigorfile script.

For details about the capabilities involved in customizing the Hvigor plugin, see Using APIs for Extending Your Build.

File Name and Path of the Custom Build Output

Scenario:

The following uses the HAR package generated by the library module as an example. By default, the HAR package build output is generated in the library/build/default/outputs/default path, and the file name is library.har.

In the production environment, you may need to save the compilation output to a specified path and change the file name based on the project requirements. For example, a file name with a version number or a file name with a developer name.

In the following example, the attributes configured in oh-package.json5 are used to change the name of the HAR package, and the output path is changed to library/build/default/outputs/target.

How to Develop:

  1. Initialize the TypeScript project. Configure the npm environment, install the TypeScript dependencies, and create an npm project as the plugin project.
  2. Develop a plugin. Configure the HarmonyOS image repository for the plugin project, install the Hvigor development dependencies, and develop the plugin. The plugin logic implementation is as follows:

    1. In the custom-plugin.ts file, write the task function renameHarTask().
    2. Use the pluginContext.registerTask() method to register a custom task in the function.
    3. Obtain modulePath and moduleName through taskContext, and concatenate them to obtain the original file path of the compilation output.
    4. Read the configuration attributes in oh-package.json5 as required and concatenate them to generate the target file name.
    5. Use fs.mkdir() to create a specified directory, and then call fs.rename() to move the compilation output to the target path and change the file name.

    The following is an example of the plugin code:

    import fs from 'fs';
    import path from 'path';
    
    interface OhPackage {
      name: string;
      version: number;
      description: string;
      author: string;
    }
    
    export function renameHarTask(str?: string) {
      return {
        pluginId: 'RenameHarTaskID',
        apply(pluginContext) {
          pluginContext.registerTask({
            // Write custom tasks
            name: 'renameHarTask',
            run: (taskContext) => {
              // Read oh-package.json5 and parse the version
              const packageFile = path.join(taskContext.modulePath, 'oh-package.json5');
              let fileContent = fs.readFileSync(packageFile, 'utf8');
              const content: OhPackage = JSON.parse(fileContent);
              const version = content.version;
              const author = content.author;
              const sourceFile = path.join(taskContext.modulePath, 'build/default/outputs/default', `${taskContext.moduleName}.har`);
              const targetPath = path.join(taskContext.modulePath, 'build/default/outputs/target');
              const targetFile = path.join(targetPath, `${taskContext.moduleName}-${version}-${author}.har`);
    
              // Create Directory
              fs.mkdir(targetPath, { recursive: true }, (err) => {
                if (err) {
                  throw err;
                }
                // Move and modify product file names
                fs.rename(sourceFile, targetFile, (err) => {
                });
              });
            },
            // Confirm custom task insertion position
            dependencies: ['default@PackageHar'],
            postDependencies: ['assembleHar']
          })
        }
      }
    }

  3. Share the plugin in either of the following ways:

    • Publishing the plugin: Pack the plugin in compliance with the npm release specifications and release it to a public or self-built image repository.
    • Using the offline package: Compress the plugin project and share it.

  4. Use the plugin. In the hvigor/hvigor-config.json5 file of your project, add the plugin dependency under the dependencies node, for example, "@bpta/custom_plugin": "1.0.0". Then, choose File > Sync and Refresh Project from the DevEco Studio menu to synchronize the project. After synchronization, import and use the plugin methods in the hvigorfile.ts file of the module. Sample code:

    import { harTasks } from '@ohos/hvigor-ohos-plugin';
    import { renameHarTask } from '@bpta/custom_plugin';
    
    export default {
      system: harTasks, /* Built-in plugin of Hvigor. It cannot be modified. */
      plugins: [renameHarTask()]         /* Custom plugin to extend the functionality of Hvigor. */
    }

  5. Choose Build > Make Module to build the project. The compilation output file is renamed name-version-author.har, and the output path is changed from the default directory to the target directory. The following figure shows the result.