目录

Basic Build Capabilities

Hvigor Object

hvigor is a predefined object used to indicate an instance of the Hvigor build engine being executed. You can use this object to obtain build information and perform related operations.

[h2]Modules to Import

import { hvigor } from '@ohos/hvigor';

[h2]getRootNode

getRootNode(): HvigorNode

Obtains the node object of the root project. This API must be used in the nodesInitialized and later phases. Otherwise, an error is reported.

Since: Hvigor 4.3.0

Returns

Type

Description

HvigorNode

Root HvigorNode object.

Example

import { hvigor } from '@ohos/hvigor';
const rootNode = hvigor.getRootNode();

[h2]getAllNodes

getAllNodes(): HvigorNode[]

Obtains an array of all node objects. Make sure the node is initialized before calling this API. Attempting to call it before initialization will result in an error.

Since: Hvigor 4.3.0

Returns

Type

Description

HvigorNode[]

Array of all HvigorNode objects.

Example

import { hvigor } from '@ohos/hvigor';
const allNodes = hvigor.getAllNodes();

[h2]getNodeByName

getNodeByName(nodeName: string, classKind?: string): HvigorNode | undefined

Obtains a node object based on the node name. Make sure the node is initialized before calling this API. Attempting to call it before initialization will result in an error.

Since: Hvigor 4.3.0

Parameters

Name

Type

Mandatory

Description

nodeName

String

Yes

Node name, that is, the project name or module name.

classKind

String

No

Node type.

When the project name is the same as the module name, use this parameter to specify which node object to obtain (the project or module). The following values are supported:

  • project: Return the node object of the project when the project name is the same as the module name.
  • module: Return the node object of the module when the project name is the same as the module name.
  • node (default): Return the node object of the module when the project name is the same as the module name.

Returns

Type

Description

HvigorNode | undefined

Node object found based on the name. If the node object does not exist, undefined is returned.

Example

import { hvigor } from '@ohos/hvigor';
const entryNode = hvigor.getNodeByName('entry');

[h2]getHvigorConfig

getHvigorConfig(): HvigorConfig

Obtains the HvigorConfig object.

Since: Hvigor 4.3.0

Returns

Type

Description

HvigorConfig

HvigorConfig object.

Example

import { hvigor } from '@ohos/hvigor';
const hvigorConfig = hvigor.getHvigorConfig();

[h2]getParameter

getParameter(): Parameter

Obtains the Parameter object.

Since: Hvigor 4.3.0

Returns

Type

Description

Parameter

Parameter object.

Example

import { hvigor } from '@ohos/hvigor';
const parameter = hvigor.getParameter();

[h2]getHvigorVersion

getHvigorVersion(): string

Obtains the Hvigor version number.

Since: Hvigor 6.22.3

Returns

Type

Description

String

Hvigor version.

Example

import { hvigor } from '@ohos/hvigor';
const hvigorVersion = hvigor.getHvigorVersion();

[h2]configEvaluated

configEvaluated(fn: (HvigorConfig) => {}): void

Adds a callback to be invoked after the config file is evaluated.

Since: Hvigor 4.3.0

Parameters

Name

Type

Mandatory

Description

fn

(HvigorConfig) => {}

Yes

A method that takes either no parameters or an hvigorConfig object.

This API is effective only when included in the hvigorconfig.ts file and is executed in the initialization phase of the build lifecycle.

Example: registering the configEvaluated hook

// hvigorconfig.ts file
import { hvigor } from '@ohos/hvigor'
hvigor.configEvaluated(hvigorConfig => {
    console.log('configEvaluated');
})

[h2]beforeNodeEvaluate

beforeNodeEvaluate(fn: (HvigorNode) => {}): void

Adds a callback to be invoked before node evaluation for all nodes.

Since: Hvigor 4.3.0

Parameters

Name

Type

Mandatory

Description

fn

(HvigorNode) => {}

Yes

A method that takes either no parameters or an HvigorNode object.

This API is effective only when included in the hvigorconfig.ts file and is executed in the initialization phase of the build lifecycle.

Example: registering the beforeNodeEvaluate hook

// hvigorconfig.ts file
import { hvigor } from '@ohos/hvigor';
hvigor.beforeNodeEvaluate(hvigorNode => {
  console.log('beforeNodeEvaluate');
})

[h2]afterNodeEvaluate

afterNodeEvaluate(fn: (HvigorNode) => {}): void

Adds a callback to be invoked after node evaluation for all nodes.

Since: Hvigor 4.3.0

Parameters

Name

Type

Mandatory

Description

fn

(HvigorNode) => {}

Yes

A method that takes either no parameters or an HvigorNode object.

Example: registering the afterNodeEvaluate hook

import { hvigor } from '@ohos/hvigor';
hvigor.afterNodeEvaluate(hvigorNode => {
  console.log('afterNodeEvaluate');
})

[h2]nodesInitialized

nodesInitialized(fn: (Hvigor) => {}): void

Adds a callback to be invoked when the node is initialized.

Since: Hvigor 4.3.0

Parameters

Name

Type

Mandatory

Description

fn

(Hvigor) => {}

Yes

A method that takes either no parameters or an Hvigor object.

This API is effective only when included in the hvigorconfig.ts file and is executed in the initialization phase of the build lifecycle.

Example: registering the nodesInitialized hook

// hvigorconfig.ts file
import { hvigor } from '@ohos/hvigor';
hvigor.nodesInitialized(() => {
  console.log('nodesInitialized');
})

[h2]nodesEvaluated

nodesEvaluated(fn: (Hvigor) => {}): void

Adds a callback to be executed after the Hvigor configuration phase completes. To take effect, this API must be called before the configuration phase ends. Use cases include delaying access to node plugin context, delaying task registration, and more, in the configuration phase. The added callbacks are stored in a queue and follow the first-in-first-out (FIFO) principle, which allows the first callback added to be invoked first.

Since: Hvigor 4.0.2

Parameters

Name

Type

Mandatory

Description

fn

(Hvigor) => {}

Yes

A method that takes either no parameters or an Hvigor object.

Example: obtaining the plugin context of a child node

In Hvigor, the project node plugins are loaded prior to the module node plugins. You can use this API to obtain the context of the task registered by a child node. The callback added will be invoked after all nodes are loaded.
import { hvigor } from '@ohos/hvigor';
import { OhosHapContext, OhosPluginId } from "@ohos/hvigor-ohos-plugin";
hvigor.nodesEvaluated(() => {
  // Obtain child node information after all nodes are loaded.
  hvigor.getRootNode().subNodes(subNode => {
    const hapContext = subNode.getContext(OhosPluginId.OHOS_HAP_PLUGIN) as OhosHapContext;
  });
});

[h2]taskGraphResolved

taskGraphResolved(fn: (Hvigor) => {}): void

Adds a callback to be invoked when the task graph is resolved.

Since: Hvigor 4.3.0

Parameters

Name

Type

Mandatory

Description

fn

(Hvigor) => {}

Yes

A method that takes either no parameters or an Hvigor object.

Example: adding a callback to be invoked when the task graph is resolved
import { hvigor } from '@ohos/hvigor';
hvigor.taskGraphResolved(() => {
  console.log('taskGraphResolved');
});

[h2]buildFinished

buildFinished(fn: (BuildResult) => {}): void

Adds a callback to be invoked when the build is complete.

Since: Hvigor 4.3.0

Parameters

Name

Type

Mandatory

Description

fn

(BuildResult) => {}

Yes

A method that takes either no parameters or a BuildResult object.

Example: obtaining build completion information and printing logs if the build terminates abnormally
import { hvigor } from '@ohos/hvigor';
hvigor.buildFinished(buildResult => {
  if (buildResult.getError()) {
    console.log(buildResult.getError().stack);
  }
})

[h2]getCommandEntryTask

getCommandEntryTask(): string[] | undefined

Obtains the array of names of the entry tasks for the build.

Since: Hvigor 4.3.0

Returns

Type

Description

string[] | undefined

Array of names of the entry tasks for the build. If the entry tasks do not exist, undefined is returned.

Example: obtaining the entry tasks and printing them out
import { hvigor } from '@ohos/hvigor';
console.log(hvigor.getCommandEntryTask());

[h2]isCommandEntryTask

isCommandEntryTask(taskName: string): boolean

Checks whether this task is an entry task for the command.

Since: Hvigor 4.3.0

Parameters

Name

Type

Mandatory

Description

taskName

String

Yes

Task name.

Returns

Type

Description

Boolean

Whether the task is an entry task.

Example: checking whether the task is an assembleHap task and printing it out
import { hvigor } from '@ohos/hvigor';
console.log(hvigor.isCommandEntryTask('assembleHap'));

getNode

getNode(scriptPath: string): HvigorNode | undefined

Obtains the current node object by passing the hvigorfile.ts script file path. If the input parameter scriptPath does not point to the hvigorfile.ts file in the project, undefined is returned.

Since: Hvigor 4.0.2

Parameters

Name

Type

Mandatory

Description

scriptPath

String

Yes

Full path of the hvigorfile.ts file.

Returns

Type

Description

HvigorNode | undefined

Hvigor node object. If the input parameter scriptPath does not point to the hvigorfile.ts file in the project, undefined is returned.

Example: obtaining the current node object

import { getNode } from "@ohos/hvigor";
const node = getNode(__filename);

BuildResult

Represents an object that encapsulates the build result; if the build ends exceptionally, it will contain information about the exception.

[h2]getError

getError(): Error | null

Obtains the error information. If no error occurs, null is returned.

Since: Hvigor 4.3.0

Returns

Type

Description

Error | null

Error information. If no error occurs, null is returned.

Example: obtaining build completion information and printing logs if the build terminates abnormally
import { hvigor } from '@ohos/hvigor';
hvigor.buildFinished(buildResult => {
  if (buildResult.getError()) {
    console.log(buildResult.getError().stack);
  }
})

[h2]getReportJson

getReportJson(): any

Obtains the visualization record report.json for the current build.

Since: Hvigor 5.0.10

Returns

Type

Description

Any

Visualization record report.json for the current build.

Different types of build events have different structures; the following is a typical structure example:

// report.json
{
  "version": "2.0", // Fixed field
  "ppid": 524, // process.ppid
  "events": [ // Build events
    ...
    {
      "head": {
        "id": "61068546-11d9-49d0-baa7-733e167af7d6", // Event ID
        "name": "Finished :entry:default@PreBuild", // Event name
        "description": "Pre-build in the stage model.",// Description
        "type": "log" // Type
      },
      "body": {
        "pid": 3960, // Process PID
        "tid": "Main Thread", // Thread ID
        "startTime": 1280741873226000, // Start time
        "endTime": 1280741896325200, // End time
        "totalTime": 22868300 // Total time
      },
      "additional": {
        "logType": "info", // Log type
        "children": [], // Child event ID list
      }
    }
  ],
  "workLog": []
}

Example

// Project-level hvigorfile.ts file
import { appTasks } from '@ohos/hvigor-ohos-plugin';
import { hvigor, FileUtil } from '@ohos/hvigor';

hvigor.buildFinished(buildResult => {
  // Write data to the file at the specified path.
  const json5FilePath = FileUtil.pathResolve('D:\\', 'testJson.json5');
  FileUtil.ensureFileSync(json5FilePath);
  FileUtil.writeFileSync(json5FilePath, JSON.stringify(buildResult.getReportJson(), null, 2));
})

export default {
    system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
    plugins:[]         /* Custom plugin to extend the functionality of Hvigor. */
}

HvigorConfig

Represents an object used to save the description of each node before the node object is created.

[h2]getRootNodeDescriptor

getRootNodeDescriptor(): HvigorNodeDescriptor

Obtains the descriptor object of the root node.

Since: Hvigor 4.3.0

Returns

Type

Description

HvigorNodeDescriptor

Descriptor object of the root node.

Example: obtaining an array of all node descriptor objects
import { hvigor } from '@ohos/hvigor';
const rootNodeDescriptor = hvigor.getHvigorConfig().getRootNodeDescriptor();

[h2]getAllNodeDescriptor

getAllNodeDescriptor(): HvigorNodeDescriptor[]

Obtains an array of all node descriptor objects.

Since: Hvigor 4.3.0

Returns

Type

Description

HvigorNodeDescriptor[]

Array of all node descriptor objects.

Example
import { hvigor } from '@ohos/hvigor';
const allNodeDescriptors = hvigor.getHvigorConfig().getAllNodeDescriptor();

[h2]getNodeDescriptorByName

getNodeDescriptorByName(name: string): HvigorNodeDescriptor

Obtains a node descriptor object by node name.

Since: Hvigor 4.3.0

Parameters

Name

Type

Mandatory

Description

name

String

Yes

Node name.

Returns

Type

Description

HvigorNodeDescriptor

Node descriptor object obtained by node name.

Example
import { hvigor } from '@ohos/hvigor';
const entryNodeDescriptors = hvigor.getHvigorConfig().getNodeDescriptorByName('entry');

[h2]includeNode

includeNode(name: string, srcPath: string, extraOptions?: Record<string, any>): void

Includes a node.

Since: Hvigor 5.4.0

Parameters

Name

Type

Mandatory

Description

name

String

Yes

Node name.

srcPath

String

Yes

Source path of the node.

extraOptions

Record<string, any>

No

Extra configuration, which will be parsed as the targets of the node.

This API is effective only when included in the hvigorconfig.ts file and is executed in the initialization phase of the build lifecycle.

Example 1: adding a node named exampleNodeName without extra configuration information
// hvigorconfig.ts file
import { hvigor } from '@ohos/hvigor';

const hvigorConfig = hvigor.getHvigorConfig();
hvigorConfig.includeNode('exampleNodeName', './exampleNodeName');
Example 2: adding a node named exampleNodeName with targets information
// hvigorconfig.ts file
import { hvigor } from '@ohos/hvigor';

const hvigorConfig = hvigor.getHvigorConfig();
hvigorConfig.includeNode('exampleNodeName', './exampleNodeName', {
  "targets": [
    {
      "name": "default",
      "applyToProducts": [
        "default"
      ]
    },
    {
      "name": "targetTest1",
      "applyToProducts": [
        "default"
      ]
    }
  ]
});

[h2]excludeNodeByName

excludeNodeByName(name: string): void

Excludes a node by name.

DevEco Studio 6.0.0 Beta3 and later versions allow you to exclude missing modules from the project. For details, see Executing ohpm install Using Hvigor.

Since: Hvigor 5.4.0

Parameters

Name

Type

Mandatory

Description

name

String

Yes

Node name.

This API is effective only when included in the hvigorconfig.ts file and is executed in the initialization phase of the build lifecycle.

Example: excluding the node named exampleNodeName
// hvigorconfig.ts file
import { hvigor } from '@ohos/hvigor';

const hvigorConfig = hvigor.getHvigorConfig();
hvigorConfig.excludeNodeByName('exampleNodeName');

HvigorNodeDescriptor

Represents a node descriptor object of Hvigor. Hvigor uses this object to construct the hvigorNode object during the build process.

[h2]Properties

Member

Type

Read-Only

Description

Available Since

name

String

No

Node name.

Hvigor 4.3.0

srcPath

String

No

Source path of the node.

Hvigor 4.3.0

extraOptions

Map<string, any>

No

Custom properties to save passed data.

Hvigor 4.3.0

[h2]getChildNode

getChildNode(): HvigorNodeDescriptor[] | undefined

Obtains all child node descriptors; returns undefined if no child nodes exist.

Since: Hvigor 4.3.0

Returns

Type

Description

HvigorNodeDescriptor[] | undefined

All child node descriptor objects. undefined is returned if no child nodes exist.

Example

// hvigorconfig.ts
import { hvigorConfig } from '@ohos/hvigor';
const rootNodeDescriptors = hvigorConfig.getRootNodeDescriptor();
rootNodeDescriptors.getChildNode()?.forEach(child => {
  console.log(`child: ${child.name}`);
});

[h2]getRootNode

getRootNode(): HvigorNodeDescriptor

Obtains the descriptor object of the root node.

Since: Hvigor 4.3.0

Returns

Type

Description

HvigorNodeDescriptor

Descriptor object of the root node.

Example

// hvigorconfig.ts
import { hvigorConfig } from '@ohos/hvigor';
const entryNodeDescriptor = hvigorConfig.getNodeDescriptorByName('entry');
console.log(`rootNode name: ${entryNodeDescriptor.getRootNode().name}`);

Product

Provides access to product information in the project-level configuration for your HarmonyOS app. You can obtain the Product instance via getCurrentProduct of OhosAppContext before calling this API.

[h2]Modules to Import

import { Product } from '@ohos/hvigor-ohos-plugin';

[h2]getProductName

getProductName: () => string

Obtains the product name.

Returns

Type

Description

String

Product name.

Example

// Project-level hvigorfile.ts file
import { hvigor, HvigorNode, HvigorPlugin } from '@ohos/hvigor';
import { appTasks, OhosAppContext, OhosPluginId, Product } from '@ohos/hvigor-ohos-plugin';
// Implement a custom plugin.
export function customPlugin(): HvigorPlugin {
  return {
    pluginId: 'customPlugin',
    async apply(currentNode: HvigorNode): Promise<void> {
      hvigor.nodesEvaluated(async () => {
        const context: OhosAppContext = currentNode.getContext(OhosPluginId.OHOS_APP_PLUGIN) as OhosAppContext;
        const currentProduct: Product = context.getCurrentProduct();
        console.log(currentProduct.getProductName());
      });
    }
  };
}
export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[customPlugin()]         /* Custom plugin to extend the functionality of Hvigor. */
}

[h2]getBundleType

getBundleType: () => string

Obtains the value of bundleType used by the product.

Returns

Type

Description

String

Value of bundleType.

Example

// Project-level hvigorfile.ts file
import { hvigor, HvigorNode, HvigorPlugin } from '@ohos/hvigor';
import { appTasks, OhosAppContext, OhosPluginId, Product } from '@ohos/hvigor-ohos-plugin';
// Implement a custom plugin.
export function customPlugin(): HvigorPlugin {
  return {
    pluginId: 'customPlugin',
    async apply(currentNode: HvigorNode): Promise<void> {
      hvigor.nodesEvaluated(async () => {
        const context: OhosAppContext = currentNode.getContext(OhosPluginId.OHOS_APP_PLUGIN) as OhosAppContext;
        const currentProduct: Product = context.getCurrentProduct();
        console.log(currentProduct.getBundleType());
      });
    }
  };
}

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[customPlugin()]         /* Custom plugin to extend the functionality of Hvigor. */
}

[h2]getBundleName

getBundleName: () => string

Obtains the value of bundleName used by the product.

Returns

Type

Description

String

Value of bundleName.

Example

// Project-level hvigorfile.ts file
import { hvigor, HvigorNode, HvigorPlugin } from '@ohos/hvigor';
import { appTasks, OhosAppContext, OhosPluginId, Product } from '@ohos/hvigor-ohos-plugin';
// Implement a custom plugin.
export function customPlugin(): HvigorPlugin {
  return {
    pluginId: 'customPlugin',
    async apply(currentNode: HvigorNode): Promise<void> {
      hvigor.nodesEvaluated(async () => {
        const context: OhosAppContext = currentNode.getContext(OhosPluginId.OHOS_APP_PLUGIN) as OhosAppContext;
        const currentProduct: Product = context.getCurrentProduct();
        console.log(currentProduct.getBundleName());
      });
    }
  };
}
export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[customPlugin()]         /* Custom plugin to extend the functionality of Hvigor. */
}

[h2]getOutputArtifactName

getOutputArtifactName: () => string | undefined

Obtains the custom app bundle name, namely the value of artifactName under product in the project-level build-profile.json5 file. undefined is returned if artifactName is not configured.

Since: Hvigor 6.22.2

Returns

Type

Description

String | undefined

Custom app bundle name. If it does not exist, undefined is returned.

Example

// Project-level hvigorfile.ts file
import { hvigor, HvigorNode, HvigorPlugin } from '@ohos/hvigor';
import { appTasks, OhosAppContext, OhosPluginId, Product } from '@ohos/hvigor-ohos-plugin';

// Implement a custom plugin.
export function customPlugin(): HvigorPlugin {
  return {
    pluginId: 'customPlugin',
    async apply(currentNode: HvigorNode): Promise<void> {
      hvigor.nodesEvaluated(async () => {
        const context: OhosAppContext = currentNode.getContext(OhosPluginId.OHOS_APP_PLUGIN) as OhosAppContext;
        const currentProduct: Product = context.getCurrentProduct();
        console.log(currentProduct.getOutputArtifactName());
      });
    }
  };
}

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[customPlugin()]         /* Custom plugin to extend the functionality of Hvigor. */
}

Target

Provides access to target information in the module-level configuration for your HarmonyOS app.

[h2]Modules to Import

import { Target } from '@ohos/hvigor-ohos-plugin';

[h2]getCurrentProduct

getCurrentProduct: () => Product

Obtains the product configured for the current target.

Returns

Type

Description

Product

Product object for the target build.

Example

// Project-level hvigorfile.ts file
import { appTasks, OhosHapContext, OhosPluginId, Target } from '@ohos/hvigor-ohos-plugin';
import { hvigor, HvigorNode } from '@ohos/hvigor';

hvigor.nodesEvaluated(() => {
  const rootNode = hvigor.getRootNode();
  rootNode.subNodes((node: HvigorNode) => {
    const hapContext = node.getContext(OhosPluginId.OHOS_HAP_PLUGIN) as OhosHapContext;
    if (!hapContext) {
      return
    }
    hapContext.targets((target: Target) => {
      // Processing logic for each target
      const currentProduct = target.getCurrentProduct();
      console.log(`Product Name: ${currentProduct.getProductName()}`);
    });
  });
})

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[]         /* Custom plugin to extend the functionality of Hvigor. */
}

[h2]getBuildTargetOutputPath

getBuildTargetOutputPath: () => string

Obtains the output path of the current target build.

Returns

Type

Description

String

Output path of the current target build.

Example

// Project-level hvigorfile.ts file
import { appTasks, OhosHapContext, OhosPluginId, Target } from '@ohos/hvigor-ohos-plugin';
import { hvigor, HvigorNode } from '@ohos/hvigor';

hvigor.nodesEvaluated(() => {
  const rootNode = hvigor.getRootNode();
  rootNode.subNodes((node: HvigorNode) => {
    const hapContext = node.getContext(OhosPluginId.OHOS_HAP_PLUGIN) as OhosHapContext;
    if (!hapContext) {
      return
    }
    hapContext.targets((target: Target) => {
      // Processing logic for each target
      const buildTargetOutputPath = target.getBuildTargetOutputPath();
      console.log(`Build Target Output Path: ${buildTargetOutputPath}`);
    });
  });
})

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[]         /* Custom plugin to extend the functionality of Hvigor. */
}

[h2]getTargetName

getTargetName: () => string

Obtains the target name.

Returns

Type

Description

String

Target name.

Example

// Project-level hvigorfile.ts file
import { appTasks, OhosHapContext, OhosPluginId, Target } from '@ohos/hvigor-ohos-plugin';
import { hvigor, HvigorNode } from '@ohos/hvigor';

hvigor.nodesEvaluated(() => {
  const rootNode = hvigor.getRootNode();
  rootNode.subNodes((node: HvigorNode) => {
    const hapContext = node.getContext(OhosPluginId.OHOS_HAP_PLUGIN) as OhosHapContext;
    if (!hapContext) {
      return
    }
    hapContext.targets((target: Target) => {
      // Processing logic for each target
      const targetName = target.getTargetName();
      console.log(`Target Name: ${targetName}`);
    });
  });
})

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[]         /* Custom plugin to extend the functionality of Hvigor. */
}

[h2]getBuildOption

getBuildOption: () => BuildOption

Obtains the buildOption information used by the module target during the current build.

Since: Hvigor 5.8.9

Returns

Type

Description

BuildOption

buildOption information used by the module target during the current build.

Example

// Project-level hvigorfile.ts file
import { appTasks, OhosHapContext, OhosPluginId, Target } from '@ohos/hvigor-ohos-plugin';
import { hvigor, HvigorNode } from '@ohos/hvigor';

hvigor.nodesEvaluated(() => {
  const rootNode = hvigor.getRootNode();
  rootNode.subNodes((node: HvigorNode) => {
    const hapContext = node.getContext(OhosPluginId.OHOS_HAP_PLUGIN) as OhosHapContext;
    if (!hapContext) {
      return
    }
    hapContext.targets((target: Target) => {
      // Processing logic for each target
      const buildOption = target.getBuildOption();
      console.log(`Build Option: ${JSON.stringify(buildOption, null, 2)}`);
    });
  });
})

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[]         /* Custom plugin to extend the functionality of Hvigor. */
}

[h2]getModulePathDetails

getModulePathDetails: () => PathDetails

Obtains the module-level path information.

Since: Hvigor 6.0.4

Returns

Type

Description

PathDetails

Module-level path information.

Example

// Project-level hvigorfile.ts file
import { appTasks, OhosHapContext, OhosPluginId, Target } from '@ohos/hvigor-ohos-plugin';
import { hvigor, HvigorNode } from '@ohos/hvigor';

hvigor.nodesEvaluated(() => {
  const rootNode = hvigor.getRootNode();
  rootNode.subNodes((node: HvigorNode) => {
    const hapContext = node.getContext(OhosPluginId.OHOS_HAP_PLUGIN) as OhosHapContext;
    if (!hapContext) {
      return
    }
    hapContext.targets((target: Target) => {
      // Processing logic for each target
      const modulePathDetails = target.getModulePathDetails();
      console.log(`Module Build Path: ${modulePathDetails.getModuleBuildPath()}`);
    });
  });
})

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[]         /* Custom plugin to extend the functionality of Hvigor. */
}

PathDetails

Represents the module-level path information. Before calling the PathDetails API, you can use the getModulePathDetails method to obtain this object.

[h2]getModuleBuildPath(): string

Obtains the build root directory of the module build product.

Since: Hvigor 6.0.4

Returns

Type

Description

String

Build root directory of the module build product, for example, "D:\MyApplication\entry\build".

Example

// Project-level hvigorfile.ts file
import { appTasks, OhosHapContext, OhosPluginId, Target } from '@ohos/hvigor-ohos-plugin';
import { hvigor, HvigorNode } from '@ohos/hvigor';

hvigor.nodesEvaluated(() => {
  const rootNode = hvigor.getRootNode();
  rootNode.subNodes((node: HvigorNode) => {
    const hapContext = node.getContext(OhosPluginId.OHOS_HAP_PLUGIN) as OhosHapContext;
    if (!hapContext) {
      return
    }
    hapContext.targets((target: Target) => {
      // Processing logic for each target
      const modulePathDetails = target.getModulePathDetails();
      console.log(`Module Build Path: ${modulePathDetails.getModuleBuildPath()}`);
    });
  });
})

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[]         /* Custom plugin to extend the functionality of Hvigor. */
}

[h2]getModuleBuildCachePath(): string

Obtains the cache directory of the intermediate build products of a module.

Since: Hvigor 6.0.4

Returns

Type

Description

String

Cache directory of the intermediate build products of a module, for example, "D:\MyApplication\entry\build\default\cache\default".

Example

// Project-level hvigorfile.ts file
import { appTasks, OhosHapContext, OhosPluginId, Target } from '@ohos/hvigor-ohos-plugin';
import { hvigor, HvigorNode } from '@ohos/hvigor';

hvigor.nodesEvaluated(() => {
  const rootNode = hvigor.getRootNode();
  rootNode.subNodes((node: HvigorNode) => {
    const hapContext = node.getContext(OhosPluginId.OHOS_HAP_PLUGIN) as OhosHapContext;
    if (!hapContext) {
      return
    }
    hapContext.targets((target: Target) => {
      // Processing logic for each target
      const modulePathDetails = target.getModulePathDetails();
      console.log(`Module Build Cache Path: ${modulePathDetails.getModuleBuildCachePath()}`);
    });
  });
})

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[]         /* Custom plugin to extend the functionality of Hvigor. */
}

[h2]getIntermediatesRes(): string

Obtains the resource cache directory generated after a module is built.

Since: Hvigor 6.0.4

Returns

Type

Description

String

Resource cache directory generated after a module is built, for example, "D:\MyApplication\entry\build\default\intermediates\res\default".

Example

// Project-level hvigorfile.ts file
import { appTasks, OhosHapContext, OhosPluginId, Target } from '@ohos/hvigor-ohos-plugin';
import { hvigor, HvigorNode } from '@ohos/hvigor';

hvigor.nodesEvaluated(() => {
  const rootNode = hvigor.getRootNode();
  rootNode.subNodes((node: HvigorNode) => {
    const hapContext = node.getContext(OhosPluginId.OHOS_HAP_PLUGIN) as OhosHapContext;
    if (!hapContext) {
      return
    }
    hapContext.targets((target: Target) => {
      // Processing logic for each target
      const modulePathDetails = target.getModulePathDetails();
      console.log(`Intermediates Res Path: ${modulePathDetails.getIntermediatesRes()}`);
    });
  });
})

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[]         /* Custom plugin to extend the functionality of Hvigor. */
}

Parameter

Represents the command configuration parameter object in Hvigor, which can be obtained through hvigor.getParameter().

[h2]getProperty

getProperty(key: string): any | undefined

Obtains a property value. If the value does not exist, undefined is returned.

Since: Hvigor 4.1.2

You can run the following command to configure properties in key-value pairs or configure it in the hvigor-config.json5 file. If different values are configured for the same key, the value configured by the command takes precedence over the value configured in the configuration file.

Parameters

Name

Type

Mandatory

Description

key

String

Yes

Key of the property to obtain.

Returns

Type

Description

Any | undefined

Value (a string, number, or boolean) obtained. If no value is specified, undefined is returned.

Example

Add code to hvigorfile.ts.

import { hvigor } from '@ohos/hvigor';
const key = hvigor.getParameter().getProperty('key');
console.log(key);

Run the hvigorw --sync -c properties.key=hello command. The following information is displayed on the console:

hello

[h2]getProperties

getProperties(): Properties

Obtains all properties.

Since: Hvigor 4.1.2

Returns

Type

Description

Properties

All properties obtained.

Example

Add code to hvigorfile.ts.

import { hvigor } from '@ohos/hvigor';
const properties = hvigor.getParameter().getProperties();
console.log(properties['key']);

Run the hvigorw --sync -c properties.key=hello command. The following information is displayed on the console:

hello

[h2]setProperty

setProperty(key: string, value: any): void

Sets a property.

Since: Hvigor 5.10.3

Parameters

Name

Type

Mandatory

Description

key

String

Yes

Key of the properties field in the hvigor-config.json5 file.

value

Any

Yes

Value corresponding to the key of the properties field in the hvigor-config.json5 file.

Call this API in the project-level hvigorfile.ts file. Calling it in the module-level hvigorfile.ts file does not take effect.

Example

// Project-level hvigorfile.ts file
import {hvigor, HvigorPlugin} from '@ohos/hvigor';
import {appTasks} from '@ohos/hvigor-ohos-plugin';

export function plugin(): HvigorPlugin{
  console.log('before: ', hvigor.getParameter().getProperty('hvigor.analyzeHtml')); // undefined
  hvigor.getParameter().setProperty('hvigor.analyzeHtml', true);
  return {
    pluginId:'example',
    apply: (node) => {
      console.log('after: ', hvigor.getParameter().getProperty('hvigor.analyzeHtml')); // true
    }
  };
}

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins: [plugin()]         /* Custom plugin to extend the functionality of Hvigor. */
};

[h2]getExtParam

getExtParam(key: string): string | undefined

Obtains the value of a parameter that is configured by -p in the command. If the value does not exist, undefined is returned.

Since: Hvigor 4.1.2

Parameters

Name

Type

Mandatory

Description

key

String

Yes

Key of the parameter configured by -p in the command.

Returns

Type

Description

String | undefined

Value obtained. If the value does not exist, undefined is returned.

Example

import { hvigor } from '@ohos/hvigor';
const extParam = hvigor.getParameter().getExtParam('key');
console.log(extParam);

Run the hvigorw --sync -p key=hello command. The following information is displayed on the console:

hello

[h2]getExtParams

getExtParams(): Record<string, string>

Obtains all parameters that are configured by -p in the command.

Since: Hvigor 4.1.2

Returns

Type

Description

Record<string, string>

All parameters obtained.

Example

import { hvigor } from '@ohos/hvigor';
const extParams = hvigor.getParameter().getExtParams();
console.log(extParams['key']);

Run the hvigorw --sync -p key=hello command. The following information is displayed on the console:

hello

[h2]getStartParams

getStartParams(): StartParams

Obtains Hvigor startup parameters, such as the settings of the daemon process, parallel build, incremental build, and log level.

Since: Hvigor 4.1.2

Returns

Type

Property

Description

StartParams

daemon: boolean

Whether the daemon process is enabled. The value true (default) means the daemon process is enabled; the value false means the opposite.

StartParams

parallel: boolean

Whether parallel build is enabled. The value true (default) means parallel build is enabled; the value false means the opposite.

StartParams

incremental: boolean

Whether incremental build is enabled. The value true (default) means incremental build is enabled; the value false means the opposite.

StartParams

logLevel: string

Log level, which can be info, debug, warn, error, and more.

StartParams

typeCheck: boolean

Whether the hvigorfile.ts type check is enabled. The value true means the type check is enabled; the value false (default) means the opposite.

Example

import { hvigor } from '@ohos/hvigor';
const startParams = hvigor.getParameter().getStartParams();
console.log(startParams['daemon']);
console.log(startParams['logLevel']);

[h2]getWorkspaceDir

getWorkspaceDir(): string

Obtains the Hvigor workspace directory. The workspace refers to the location where the Hvigor plugin of the current project is installed.

Since: Hvigor 4.1.2

Returns

Type

Description

String

Hvigor workspace directory.

Example

import { hvigor } from '@ohos/hvigor';
const workspaceDir = hvigor.getParameter().getWorkspaceDir();
console.log(workspaceDir);

HvigorNode

Defines the node model for Hvigor projects. Each Hvigor project has a node object corresponding to the root module and node objects corresponding to each submodule. All node objects implement the HvigorNode interface. Node objects contain the configuration, properties, and tasks of a module.

[h2]Modules to Import

import { HvigorNode } from '@ohos/hvigor';

[h2]Obtaining an Instance

You can obtain an hvigorNode instance using the following methods: getRootNode and getAllNodes on an hvigor object, getNode, and apply in HvigorPlugin.

The following uses the apply method of HvigorPlugin as an example:

import { HvigorNode, HvigorPlugin } from '@ohos/hvigor';

// Implement a custom plugin.
export function customPlugin(): HvigorPlugin {
  return {
    pluginId: 'customPlugin',
    async apply(currentNode: HvigorNode): Promise<void> {
      // Use the methods of hvigorNode through currentNode.
    }
  };
}

[h2]registerTask

registerTask: (task: HvigorTask) => void

Registers a task for this node. This API is called in the configuration phase of the Hvigor lifecycle. The HvigorTask object must be implemented and used as the input parameter.

Since: Hvigor 4.0.2

Parameters

Name

Type

Mandatory

Description

task

HvigorTask

Yes

Task to register.

Example

// For details about how to obtain the node, see Obtaining an Instance.
node.registerTask({
  name: 'customTask',
  run() {
    console.log('this is Task');
  }
});

[h2]getTaskByName

getTaskByName: (taskName: string) => Task | undefined

Obtains a registered task of this node.

Since: Hvigor 4.0.2

Parameters

Name

Type

Mandatory

Description

taskName

String

Yes

Name of the task to obtain.

Returns

Type

Description

Task | undefined

Task object obtained. If the task does not exist, undefined is returned.

Example

// For details about how to obtain the node, see Obtaining an Instance.
node.getTaskByName('assembleApp')

[h2]getNodeName

getNodeName: () => string

Obtains the name of this node.

Since: Hvigor 4.0.2

Returns

Type

Description

String

Node name obtained.

Example

// For details about how to obtain the node, see Obtaining an Instance.
const nodeName = node.getNodeName();

[h2]getNodePath

getNodePath: () => string

Obtains the path of this node.

Since: Hvigor 4.0.2

Returns

Type

Description

String

Node path obtained.

Example

// For details about how to obtain the node, see Obtaining an Instance.
const nodePath = node.getNodePath();

[h2]getParentNode

getParentNode: () => HvigorNode | undefined

Obtains the parent node of this node.

Since: Hvigor 4.0.2

Returns

Type

Description

HvigorNode | undefined

Parent node obtained, or undefined if the node does not have a parent node.

Example

// For details about how to obtain the node, see Obtaining an Instance.
const parentNode = node.getParentNode();

[h2]subNodes

subNodes: (callbackfn: (node: HvigorNode) => void) => void

Traverses all child nodes under the current node and executes a callback for each child node. This API allows you to operate on node objects from the project node.

Project nodes are loaded prior to module nodes. Before operating a child node, call hvigor.nodesEvaluated and wait until all nodes are loaded.

Since: Hvigor 4.0.2

Parameters

Name

Type

Mandatory

Description

callbackfn

(node: HvigorNode) => void

Yes

Callback with a parameter of the HvigorNode type. A void function is returned.

Example

// Project-level hvigorfile.ts
import { HvigorNode, HvigorPlugin } from '@ohos/hvigor'
import { appTasks } from '@ohos/hvigor-ohos-plugin';

export function customPlugin(): HvigorPlugin {
  return {
    pluginId: 'customPlugin',
    async apply(currentNode: HvigorNode): Promise<void> {
      currentNode.subNodes((node: HvigorNode) => {
        // Perform operations related to child nodes.
        // For example, obtain the name of the child node.
        const subNodeName = node.getNodeName();
      })
    }
  };
}

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[customPlugin()]         /* Custom plugin to extend the functionality of Hvigor. */
}

[h2]getSubNodeByName

getSubNodeByName: (nodeName: string) => HvigorNode | undefined

Obtains a node object based on the node name.

Since: Hvigor 4.0.2

Parameters

Name

Type

Mandatory

Description

nodeName

String

Yes

Node name.

Returns

Type

Description

HvigorNode | undefined

Node object obtained, or undefined if the node object does not exist.

Example

// Project-level hvigorfile.ts
import { appTasks } from '@ohos/hvigor-ohos-plugin';
import { HvigorNode, HvigorPlugin } from '@ohos/hvigor';

// In the hvigorfile.ts file in the root directory of the project, currentNode indicates the app, and its child node includes entry.
// Obtain the entry object using getSubNodeByName.
export function customPlugin(): HvigorPlugin {
  return {
    pluginId: 'customPlugin',
    async apply(currentNode: HvigorNode): Promise<void> {
      const subNode = currentNode.getSubNodeByName('entry');
    }
  };
}

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins: [customPlugin()]         /* Custom plugin to extend the functionality of Hvigor. */
}

[h2]getContext

getContext: (pluginId: string) => any

Obtains the context of a plugin of this node by plugin ID.

Since: Hvigor 4.0.2

Parameters

Name

Type

Mandatory

Description

pluginId

String

Yes

Plugin ID.

Returns

Type

Description

Any

Context obtained, whose type can be customized.

Example

// Project-level hvigorfile.ts
import { appTasks, OhosAppContext, OhosPluginId } from '@ohos/hvigor-ohos-plugin';
import { hvigor, getNode, HvigorNode, HvigorPlugin } from '@ohos/hvigor';

// Import OhosPluginId and OhosAppContext to obtain context information.
// Obtain it in the lifecycle hook.
hvigor.nodesEvaluated(() => {
  const node: HvigorNode = getNode(__filename);
  const appContext = node.getContext(OhosPluginId.OHOS_APP_PLUGIN) as OhosAppContext;
  // Use appContext to obtain context information, such as the project name.
  console.log('projectName:', appContext.getProjectName());
});
// Alternatively, obtain it directly using apply.
export function customPlugin(): HvigorPlugin {
  return {
    pluginId: 'customPlugin',
    async apply(currentNode: HvigorNode): Promise<void> {
      const appContext = currentNode.getContext(OhosPluginId.OHOS_APP_PLUGIN) as OhosAppContext;
      console.log('projectName:', appContext.getProjectName());
    }
  };
}

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins: [customPlugin()]         /* Custom plugin to extend the functionality of Hvigor. */
}

[h2]getAllPluginIds

getAllPluginIds: () => string[]

Obtains all plugins loaded by this node.

Since: Hvigor 4.0.2

Returns

Type

Description

string[]

IDs of the loaded plugins.

Example

// Project-level hvigorfile.ts
import { HvigorNode, HvigorPlugin } from '@ohos/hvigor'
import { appTasks } from '@ohos/hvigor-ohos-plugin';

export function customPlugin(): HvigorPlugin {
  return {
    pluginId: 'customPlugin',
    async apply(currentNode: HvigorNode): Promise<void> {
      const allPluginIds = currentNode.getAllPluginIds();
      allPluginIds.forEach((id) => {
        console.log(id);
      })
    }
  };
}

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins: [customPlugin()]         /* Custom plugin to extend the functionality of Hvigor. */
}

[h2]nodeDir

nodeDir: NormalizedFile

Represents NormalizedFile object of the current node's root directory.

Since: Hvigor 4.3.0

[h2]getNodeDir

getNodeDir: () => NormalizedFile

Obtains the NormalizedFile object of current node's root directory.

Since: Hvigor 4.3.0

Returns

Type

Description

NormalizedFile

NormalizedFile object of the current node's root directory.

Example

// Project-level hvigorfile.ts
import { HvigorNode, HvigorPlugin } from '@ohos/hvigor';
import { appTasks } from '@ohos/hvigor-ohos-plugin'

export function customPlugin(): HvigorPlugin {
  return {
    pluginId: 'customPlugin',
    async apply(currentNode: HvigorNode): Promise<void> {
      const dir = currentNode.getNodeDir();
    }
  };
}

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins: [customPlugin()]         /* Custom plugin to extend the functionality of Hvigor. */
}

[h2]addExtraOption

addExtraOption: (key: string, value: any) => void

Adds a custom property to the current node.

Since: Hvigor 4.3.0

Parameters

Name

Type

Mandatory

Description

key

String

Yes

Key of the custom property to add.

value

Any

Yes

Value of the custom property to add.

Example

// Project-level hvigorfile.ts
import { HvigorNode, HvigorPlugin } from '@ohos/hvigor';
import { appTasks } from '@ohos/hvigor-ohos-plugin'

export function customPlugin(): HvigorPlugin {
  return {
    pluginId: 'customPlugin',
    async apply(currentNode: HvigorNode): Promise<void> {
      currentNode.addExtraOption('key', 'value');
    }
  };
}

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins: [customPlugin()]         /* Custom plugin to extend the functionality of Hvigor. */
}

[h2]getExtraOption

getExtraOption: (key: string) => any

Obtains the custom property set on the current node using the addExtraOption() function.

Since: Hvigor 4.3.0

Parameters

Name

Type

Mandatory

Description

key

String

Yes

Key of the custom property.

Returns

Type

Description

Any

Value of the custom property.

Example

// Project-level hvigorfile.ts
import { HvigorNode, HvigorPlugin } from '@ohos/hvigor';
import { appTasks } from '@ohos/hvigor-ohos-plugin'

export function customPlugin(): HvigorPlugin {
  return {
    pluginId: 'customPlugin',
    async apply(currentNode: HvigorNode): Promise<void> {
      currentNode.addExtraOption('key', 'value');
      currentNode.getExtraOption('key');
    }
  };
}

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins: [customPlugin()]         /* Custom plugin to extend the functionality of Hvigor. */
}

[h2]beforeNodeEvaluate

beforeNodeEvaluate(fn: (HvigorNode) => {}): void

Adds a callback to be invoked before node evaluation for the current node.

Since: Hvigor 4.3.0

Parameters

Name

Type

Mandatory

Description

fn

(HvigorNode) => {}

Yes

A method that takes either no parameters or an HvigorNode object.

Example: registering a beforeNodeEvaluate hook for a node named entry and printing out the node information

import { hvigor } from '@ohos/hvigor';
hvigor.nodesInitialized(() => {
  hvigor.getRootNode().subNodes(node => {
    if (node.getNodeName() === 'entry') {
      node.beforeNodeEvaluate(hvigorNode => {
        console.log(hvigorNode.getNodeName());
      })
    }
  })
});

[h2]afterNodeEvaluate

afterNodeEvaluate(fn: (HvigorNode) => {}): void

Adds a callback to be invoked after node evaluation for the current node.

Since: Hvigor 4.3.0

Parameters

Name

Type

Mandatory

Description

fn

(HvigorNode) => {}

Yes

A method that takes either no parameters or an HvigorNode object.

Example: registering an afterNodeEvaluate hook for a node named entry and printing out the node information

import { hvigor } from '@ohos/hvigor';
hvigor.nodesInitialized(() => {
  hvigor.getRootNode().subNodes(node => {
    if (node.getNodeName() === 'entry') {
      node.afterNodeEvaluate(hvigorNode => {
        console.log(hvigorNode.getNodeName());
      })
    }
  })
});

HvigorPlugin

Defines an Hvigor plugin instance. You can use it to develop an Hvigor plugin.

[h2]Modules to Import

import { HvigorPlugin } from '@ohos/hvigor';

[h2]pluginId

pluginId: string

Represents the unique ID of the plugin.

Example

// Project-level hvigorfile.ts file
import { HvigorNode, HvigorPlugin } from '@ohos/hvigor';
import { appTasks } from '@ohos/hvigor-ohos-plugin';

// Implement a custom plugin.
export function customPlugin(): HvigorPlugin {
  return {
    pluginId: 'customPlugin',
    context() {
      return {
        data: 'customPlugin xxx'
      };
    },
    async apply(currentNode: HvigorNode): Promise<void> {
    }
  };
}

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins: [customPlugin()]         /* Custom plugin to extend the functionality of Hvigor. */
}

[h2]context

context?: (() => any) | any

Represents the context of the plugin, which is optional. You can use node.getContext('Plugin ID') to obtain the context of a plugin.

Returns

Type

Description

(() => any) | any

A value of any type or a function that returns a value of any type.

Example

// Project-level hvigorfile.ts file
import { HvigorNode, HvigorPlugin } from '@ohos/hvigor';
import { appTasks } from '@ohos/hvigor-ohos-plugin';

// Implement a custom plugin.
export function customPlugin(): HvigorPlugin {
  return {
    pluginId: 'customPlugin',
    context() {
      return {
        data: 'customPlugin xxx'
      };
    },
    async apply(currentNode: HvigorNode): Promise<void> {
    }
  };
}

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[customPlugin()]         /* Custom plugin to extend the functionality of Hvigor. */
}

[h2]apply

apply: (node: HvigorNode) => void | Promise<void>

Represents the function that defines the plugin implementation logic (for example, task registration). This API is called in the configuration phase of the Hvigor lifecycle.

Parameters

Name

Type

Mandatory

Description

node

HvigorNode

Yes

HvigorNode object obtained.

Returns

Type

Description

void | Promise<void>

No return value or a value of the Promise<void> type.

Example

// Project-level hvigorfile.ts file
import { hvigor, HvigorNode, HvigorPlugin } from '@ohos/hvigor';
import { appTasks } from '@ohos/hvigor-ohos-plugin';

// Implement a custom plugin.
export function customPlugin(): HvigorPlugin {
  return {
    pluginId: 'customPlugin',
    context() {
      return {
        data: 'customPlugin xxx'
      };
    },
    async apply(currentNode: HvigorNode): Promise<void> {
      hvigor.nodesEvaluated(async () => {
        // Register a module-level task.
      });
    }
  };
}

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[customPlugin()]         /* Custom plugin to extend the functionality of Hvigor. */
};

HvigorTask

Defines an Hvigor task instance, which is required when a task is created.

[h2]Modules to Import

import { HvigorTask } from '@ohos/hvigor';

[h2]name

name: string

Defines the task name.

Example

// Project-level hvigorfile.ts file
import { appTasks } from '@ohos/hvigor-ohos-plugin';
import { getNode, HvigorNode, HvigorTask } from '@ohos/hvigor';

// Obtain the current hvigorNode object.
const node: HvigorNode = getNode(__filename);
// Register a task.
node.registerTask({
  name: 'customTask',
  run() {
    console.log('this is Task');
  }
});

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[]         /* Custom plugin to extend the functionality of Hvigor. */
}

[h2]context

context?: (() => any) | any

Represents the data object that is partially shared in a task. This object is injected to the this.context property when the task is registered. In the input, output, and run functions, this.context can directly invoke the objects and properties defined in context.

Returns

Type

Description

(() => any) | any

A value of any type or a function that returns a value of any type.

Example

// Project-level hvigorfile.ts file
import { appTasks } from '@ohos/hvigor-ohos-plugin';
import { getNode, HvigorNode, HvigorTask } from '@ohos/hvigor';

// Obtain the current hvigorNode object.
const node: HvigorNode = getNode(__filename);
// Register a task.
node.registerTask({
  name: 'customTask',
  context() {
    return {
      data: 'customRegisterTask xxx'
    };
  },
  run() {
    console.log(this.context);
  }
});

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[]         /* Custom plugin to extend the functionality of Hvigor. */
}

[h2]input

input?: (input: TaskInput) => void

Defines the input condition for the incremental build task.

Parameters

Name

Type

Mandatory

Description

input

TaskInput

Yes

Input condition.

Example

// Project-level hvigorfile.ts file
import { appTasks, OhosAppContext, OhosPluginId } from '@ohos/hvigor-ohos-plugin';
import { getNode, hvigor, HvigorTaskContext, TaskInput, TaskOutput } from "@ohos/hvigor";
import fse from "fs-extra";
import path from "path";

const currentNode = getNode(__filename);

hvigor.nodesEvaluated(() => {
  const context = currentNode.getContext(OhosPluginId.OHOS_APP_PLUGIN) as OhosAppContext;
  const outputFilePath = path.resolve(context.getBuildRootPath(), 'test.txt');
  // Register a file generation task and enable incremental processing for this task.
  currentNode.registerTask({
    name: "testTask",
    run(taskContext: HvigorTaskContext): void | Promise<void> {
      fse.writeFileSync(outputFilePath, context.getProjectName());
      return undefined;
    },
    input(input: TaskInput): void {
      input.property('projectName', context.getProjectName());
    },
    async output(output: TaskOutput): Promise<void> {
      try {
        const parentDir = path.dirname(outputFilePath);
        await fse.ensureDir(parentDir); // Ensure that the parent directory exists.
        await fse.ensureFile(outputFilePath);
        output.file(outputFilePath);
      } catch (error) {
        console.error('File creation failed:', error);
        throw error;
      }
    },
    postDependencies: ['assembleApp']
  })
})

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[]         /* Custom plugin to extend the functionality of Hvigor. */
}

Add dependencies to hvigor-config.json5 as follows:

// hvigor-config.json5
"dependencies": {
  "fs-extra": "11.2.0",
  "@types/fs-extra": "9.0.13"
},

[h2]output

output?: (output: TaskOutput) => void

Defines the output condition for the incremental build task.

Parameters

Name

Type

Mandatory

Description

output

TaskOutput

Yes

Output condition.

Example

// Project-level hvigorfile.ts file
import { appTasks, OhosAppContext, OhosPluginId } from '@ohos/hvigor-ohos-plugin';
import { getNode, hvigor, HvigorTaskContext, TaskInput, TaskOutput } from "@ohos/hvigor";
import fse from "fs-extra";
import path from "path";

const currentNode = getNode(__filename);

hvigor.nodesEvaluated(() => {
  const context = currentNode.getContext(OhosPluginId.OHOS_APP_PLUGIN) as OhosAppContext;
  const outputFilePath = path.resolve(context.getBuildRootPath(), 'test.txt');
  // Register a file generation task and enable incremental processing for this task.
  currentNode.registerTask({
    name: "testTask",
    run(taskContext: HvigorTaskContext): void | Promise<void> {
      fse.writeFileSync(outputFilePath, context.getProjectName());
      return undefined;
    },
    input(input: TaskInput): void {
      input.property('projectName', context.getProjectName());
    },
    async output(output: TaskOutput): Promise<void> {
      try {
        const parentDir = path.dirname(outputFilePath);
        await fse.ensureDir(parentDir); // Ensure that the parent directory exists.
        await fse.ensureFile(outputFilePath);
        output.file(outputFilePath);
      } catch (error) {
        console.error('File creation failed:', error);
        throw error;
      }
    },
    postDependencies: ['assembleApp']
  })
})

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[]         /* Custom plugin to extend the functionality of Hvigor. */
}

Add dependencies to hvigor-config.json5 as follows:

// hvigor-config.json5
"dependencies": {
  "fs-extra": "11.2.0",
  "@types/fs-extra": "9.0.13"
},

[h2]run

run: (taskContext: HvigorTaskContext) => void | Promise<void>

Represents the function that defines the task logic. You can define the task processing logic in this function.

Parameters

Name

Type

Mandatory

Description

taskContext

HvigorTaskContext

No

Default common information injected.

Returns

Type

Description

void | Promise<void>

No return value or a value of the Promise<void> type.

Example

// Project-level hvigorfile.ts file
import { appTasks } from '@ohos/hvigor-ohos-plugin';
import { getNode, HvigorNode, HvigorTask } from '@ohos/hvigor';

// Obtain the current hvigorNode object.
const node: HvigorNode = getNode(__filename);
// Register a task.
node.registerTask({
  name: 'customTask',
  run() {
    console.log('this is Task');
  }
});

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[]         /* Custom plugin to extend the functionality of Hvigor. */
}

[h2]beforeRun

beforeRun?: (taskContext: HvigorTaskContext) => void | Promise<void>

Represents the function to call before run. When the task is executed, this function is called before run.

Parameters

Name

Type

Mandatory

Description

taskContext

HvigorTaskContext

No

Default common information injected.

Returns

Type

Description

void | Promise<void>

No return value or a value of the Promise<void> type.

Example

// Project-level hvigorfile.ts file
import { appTasks } from '@ohos/hvigor-ohos-plugin';
import { getNode, HvigorNode, HvigorTask } from '@ohos/hvigor';

// Obtain the current hvigorNode object.
const node: HvigorNode = getNode(__filename);
// Register a task.
node.registerTask({
  name: 'customTask',
  run() {
    console.log('customTask');
  },
  beforeRun() {
    console.log('beforeRun');
  }
});

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[]         /* Custom plugin to extend the functionality of Hvigor. */
}

[h2]afterRun

afterRun?: (taskContext: HvigorTaskContext) => void | Promise<void>

Represents the function to call after run. When the task is executed, this function is called after run.

Parameters

Name

Type

Mandatory

Description

taskContext

HvigorTaskContext

No

Default common information injected.

Returns

Type

Description

void | Promise<void>

No return value or a value of the Promise<void> type.

Example

// Project-level hvigorfile.ts file
import { appTasks } from '@ohos/hvigor-ohos-plugin';
import { getNode, HvigorNode, HvigorTask } from '@ohos/hvigor';

// Obtain the current hvigorNode object.
const node: HvigorNode = getNode(__filename);
// Register a task.
node.registerTask({
  name: 'customTask',
  run() {
    console.log('customTask');
  },
  afterRun() {
    console.log('afterRun');
  }
});

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[]         /* Custom plugin to extend the functionality of Hvigor. */
}

[h2]dependencies

dependencies?: (() => string[]) | string[]

Configures the task on which this task depends. The task execution sequence is: previous task -> this task -> next task.

Since DevEco Studio 6.0.0 Beta2, tasks that depend on other modules are supported. Add Module name: before such tasks, for example, har:assembleHar.

Returns

Type

Description

(() => string[]) | string[]

An array of strings or a function that returns an array of strings.

For tasks depending on other modules, register them in hook-nodesEvaluated. Otherwise, tasks of other modules may not be initialized during registration, and the current task cannot be registered.

Example 1: tasks that depend on the current module

// Project-level hvigorfile.ts file
import { appTasks } from '@ohos/hvigor-ohos-plugin';
import { getNode, HvigorNode, HvigorTask } from '@ohos/hvigor';

// Obtain the current hvigorNode object.
const node: HvigorNode = getNode(__filename);
// Register a task.
node.registerTask({
  name: 'customTask',
  run() {
    console.log('customTask');
  },
  dependencies: ['customTask1'],
});
// Register a task.
node.registerTask({
  name: 'customTask1',
  run() {
    console.log('customTask1');
  },
});

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[]         /* Custom plugin to extend the functionality of Hvigor. */
}

Example 2: tasks that depend on other modules

// Project-level hvigorfile.ts file
import { appTasks } from '@ohos/hvigor-ohos-plugin';
import { hvigor, HvigorNode, HvigorPlugin } from '@ohos/hvigor';

// Obtain the current entry node object.
const entryNode = hvigor.getNodeByName('entry');

// Place the logic in hook-nodesEvaluated.
hvigor.nodesEvaluated(async () => {
  // Register the task.
  entryNode.registerTask({
    // Configure the task name.
    name: `default@CustomTask`,
    run() {
      console.log('customTask1')
    },
    // Configure the previous tasks that this task depends on.
    dependencies: ['har:assembleHar'], // Cross-module dependency on the assembleHar task of the HAR module. Ensure that the HAR module exists.
    // Configure the tasks that depend on this task.
    postDependencies: ['entry:default@PreBuild']  // Two formats are supported: entry:default@PreBuild and default@PreBuild.
  });
});

export default {
  system: appTasks, /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins: []       /* Custom plugin to extend the functionality of Hvigor. */
}

[h2]postDependencies

postDependencies?: (() => string[]) | string[]

Configures the task that depends on this task. The task execution sequence is: previous task -> this task -> next task.

Since DevEco Studio 6.0.0 Beta2, tasks that depend on other modules are supported. Add Module name: before such tasks, for example, har:default@PreBuild.

Returns

Type

Description

(() => string[]) | string[]

An array of strings or a function that returns an array of strings.

For tasks depending on other modules, register them in hook-nodesEvaluated. Otherwise, tasks of other modules may not be initialized during registration, and the current task cannot be registered.

Example 1: tasks that depend on the current module

// Project-level hvigorfile.ts file
import { appTasks } from '@ohos/hvigor-ohos-plugin';
import { getNode, HvigorNode, HvigorTask } from '@ohos/hvigor';

// Obtain the current hvigorNode object.
const node: HvigorNode = getNode(__filename);
// Register a task.
node.registerTask({
  name: 'customTask1',
  run() {
    console.log('customTask1');
  },
});
// Register a task.
node.registerTask({
  name: 'customTask',
  run() {
    console.log('customTask');
  },
  postDependencies: ['customTask1'],
});

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[]         /* Custom plugin to extend the functionality of Hvigor. */
}

Example 2: tasks that depend on other modules

// Project-level hvigorfile.ts file
import { appTasks } from '@ohos/hvigor-ohos-plugin';
import { hvigor, HvigorNode, HvigorPlugin } from '@ohos/hvigor';

// Obtain the current entry node object.
const entryNode = hvigor.getNodeByName('entry');

// Place the logic in hook-nodesEvaluated.
hvigor.nodesEvaluated(async () => {
  // Register the task.
  entryNode.registerTask({
    // Configure the task name.
    name: `default@CustomTask`,
    run() {
      console.log('customTask1')
    },
    // Configure the previous task that this task depends on.
    dependencies: ['entry:default@PreBuild'], // Two formats are supported: entry:default@PreBuild and default@PreBuild.
    // Configure the tasks that depend on this task.
    postDependencies: ['har:default@PreBuild']  // Cross-module dependency on the PreBuild task of the HAR module. Ensure that the HAR module exists.
  });
});

export default {
  system: appTasks, /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins: []       /* Custom plugin to extend the functionality of Hvigor. */
}

HvigorTaskContext

Represents the task context type in Hvigor. Objects of this type are automatically bound to the context of the current task.

[h2]Properties

Member

Type

Read-Only

Description

moduleName

String

Yes

Name of the module bound to the current task.

modulePath

String

Yes

Path of the module bound to the current task.

TaskInput

Provides basic functions for adding input conditions for an incremental build task.

[h2]Modules to Import

import { TaskInput } from '@ohos/hvigor';

[h2]property

property(key: string, value: TaskInputValue): TaskInput

Adds a property in the form of a key-value pair as the input condition for an incremental build task.

Parameters

Name

Type

Mandatory

Description

key

String

Yes

Key of the property to add.

value

TaskInputValue

Yes

Value of the property to add. The value can be a number, string, boolean, or an array of them.

Returns

Type

Description

TaskInput

Task input condition used for method chaining.

Example

// Project-level hvigorfile.ts file
import { appTasks, OhosAppContext, OhosPluginId } from '@ohos/hvigor-ohos-plugin';
import { getNode, hvigor, HvigorTask, HvigorTaskContext, TaskInput, TaskOutput } from "@ohos/hvigor";
import fse from "fs-extra";
import path from "path";

const currentNode = getNode(__filename);
hvigor.nodesEvaluated(() => {
  const context = currentNode.getContext(OhosPluginId.OHOS_APP_PLUGIN) as OhosAppContext;
  const outputFilePath = path.resolve(context.getBuildRootPath(), 'test.txt');
  // Register a file generation task and enable incremental processing for this task.
  currentNode.registerTask({
    name: "testTask",
    run(taskContext: HvigorTaskContext): void | Promise<void> {
      fse.writeFileSync(outputFilePath, context.getProjectName());
      return undefined;
    },
    input(input: TaskInput): void {
      input.property('projectName', context.getProjectName());
    },
    async output(output: TaskOutput): Promise<void> {
      try {
        const parentDir = path.dirname(outputFilePath);
        await fse.ensureDir(parentDir); // Ensure that the parent directory exists.
        await fse.ensureFile(outputFilePath);
        output.file(outputFilePath);
      } catch (error) {
        console.error('File creation failed:', error);
        throw error;
      }
    },
    postDependencies: ['assembleApp']
  })
})

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[]         /* Custom plugin to extend the functionality of Hvigor. */
}

Add dependencies to hvigor-config.json5 as follows:

// hvigor-config.json5
"dependencies": {
  "fs-extra": "11.2.0",
  "@types/fs-extra": "9.0.13"
},

[h2]file

file(path: string): TaskInput

Adds the path of a file or folder as the input condition for an incremental build task.

Parameters

Name

Type

Mandatory

Description

path

String

Yes

Path to add.

Returns

Type

Description

TaskInput

Task input condition used for method chaining.

Example

// Project-level hvigorfile.ts file
import { appTasks, OhosAppContext, OhosPluginId } from '@ohos/hvigor-ohos-plugin';
import { getNode, hvigor, HvigorTask, HvigorTaskContext, TaskInput, TaskOutput } from "@ohos/hvigor";
import fse from "fs-extra";
import path from "path";

const currentNode = getNode(__filename);
hvigor.nodesEvaluated(() => {
  const context = currentNode.getContext(OhosPluginId.OHOS_APP_PLUGIN) as OhosAppContext;
  const outputFilePath = path.resolve(context.getBuildRootPath(), 'testOutput.txt');
  // Add the path of a file as the input condition for an incremental build task.
  const inputFilePath = path.resolve(context.getProjectPath(), 'testInput.txt');
  // Register a file generation task and enable incremental processing for this task.
  currentNode.registerTask({
    name: "testTask",
    run(taskContext: HvigorTaskContext): void | Promise<void> {
      const parentDir = path.dirname(outputFilePath);
      fse.ensureDirSync(parentDir); // Ensure that the parent directory exists.
      fse.ensureFileSync(outputFilePath);
      fse.writeFileSync(outputFilePath, context.getProjectName());
      return undefined;
    },
    input(input: TaskInput): void {
      input.property('projectName', context.getProjectName());
      if (fse.existsSync(inputFilePath)) {
        input.file(inputFilePath);
      }
    },
    async output(output: TaskOutput): Promise<void> {
      output.file(outputFilePath);
    },
    postDependencies: ['assembleApp']
  })
})

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[]         /* Custom plugin to extend the functionality of Hvigor. */
}

Add dependencies to hvigor-config.json5 as follows:

// hvigor-config.json5
"dependencies": {
  "fs-extra": "11.2.0",
  "@types/fs-extra": "9.0.13"
},

[h2]files

files(paths: string[]): TaskInput

Adds the paths of multiple files or folders as the input condition for an incremental build task.

Parameters

Name

Type

Mandatory

Description

paths

string[]

Yes

Paths to add.

Returns

Type

Description

TaskInput

Task input condition used for method chaining.

Example

// Project-level hvigorfile.ts file
import { appTasks, OhosAppContext, OhosPluginId } from '@ohos/hvigor-ohos-plugin';
import { getNode, hvigor, HvigorTask, HvigorTaskContext, TaskInput, TaskOutput } from "@ohos/hvigor";
import fse from "fs-extra";
import path from "path";

const currentNode = getNode(__filename);
hvigor.nodesEvaluated(() => {
  const context = currentNode.getContext(OhosPluginId.OHOS_APP_PLUGIN) as OhosAppContext;
  const outputFilePath = path.resolve(context.getBuildRootPath(), 'test.txt');
  // Add the path of a file as the input condition for an incremental build task.
  const inputFilePath = path.resolve(context.getProjectPath(), 'test.txt');
  // Register a file generation task and enable incremental processing for this task.
  currentNode.registerTask({
    name: "testTask",
    run(taskContext: HvigorTaskContext): void | Promise<void> {
      const parentDir = path.dirname(outputFilePath);
      fse.ensureDirSync(parentDir); // Ensure that the parent directory exists.
      fse.ensureFileSync(outputFilePath);
      fse.writeFileSync(outputFilePath, context.getProjectName());
      return undefined;
    },
    input(input: TaskInput): void {
      input.property('projectName', context.getProjectName());
      if (fse.existsSync(inputFilePath)) {
        input.files([inputFilePath, ]);
      }
    },
    async output(output: TaskOutput): Promise<void> {
      output.files([outputFilePath,]);
    },
    postDependencies: ['assembleApp']
  })
})

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[]         /* Custom plugin to extend the functionality of Hvigor. */
}

Add dependencies to hvigor-config.json5 as follows:

// hvigor-config.json5
"dependencies": {
  "fs-extra": "11.2.0",
  "@types/fs-extra": "9.0.13"
},

TaskOutput

Provides basic functions for adding output conditions for an incremental build task.

[h2]Modules to Import

import { TaskOutput } from '@ohos/hvigor';

[h2]file

file(path: string): TaskOutput

Adds the path of a file or folder as the output condition for an incremental build task.

Parameters

Name

Type

Mandatory

Description

path

String

Yes

Path to add.

Returns

Type

Description

TaskOutput

Task output condition used for method chaining.

Example

// Project-level hvigorfile.ts file
import { appTasks, OhosAppContext, OhosPluginId } from '@ohos/hvigor-ohos-plugin';
import { getNode, hvigor, HvigorTaskContext, TaskInput, TaskOutput } from "@ohos/hvigor";
import fse from "fs-extra";
import path from "path";

const currentNode = getNode(__filename);
hvigor.nodesEvaluated(() => {
  const context = currentNode.getContext(OhosPluginId.OHOS_APP_PLUGIN) as OhosAppContext;
  const outputFilePath = path.resolve(context.getBuildRootPath(), 'testOutput.txt');
  // Add the path of a file as the input condition for an incremental build task.
  const inputFilePath = path.resolve(context.getProjectPath(), 'testInput.txt');
  // Register a file generation task and enable incremental processing for this task.
  currentNode.registerTask({
    name: "testTask",
    run(taskContext: HvigorTaskContext): void | Promise<void> {
      const parentDir = path.dirname(outputFilePath);
      fse.ensureDirSync(parentDir); // Ensure that the parent directory exists.
      fse.ensureFileSync(outputFilePath);
      fse.writeFileSync(outputFilePath, context.getProjectName());
      return undefined;
    },
    input(input: TaskInput): void {
      input.property('projectName', context.getProjectName());
      if (fse.existsSync(inputFilePath)) {
        input.file(inputFilePath);
      }
    },
    async output(output: TaskOutput): Promise<void> {
      output.file(outputFilePath);
    },
    postDependencies: ['assembleApp']
  })
})

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[]         /* Custom plugin to extend the functionality of Hvigor. */
}

Add dependencies to hvigor-config.json5 as follows:

// hvigor-config.json5
"dependencies": {
  "fs-extra": "11.2.0",
  "@types/fs-extra": "9.0.13"
},

[h2]files

files(paths: string[]): TaskOutput

Adds the paths of multiple files or folders as the output condition for an incremental build task.

Parameters

Name

Type

Mandatory

Description

paths

string[]

Yes

Paths to add.

Returns

Type

Description

TaskOutput

Task output condition used for method chaining.

Example

// Project-level hvigorfile.ts file
import { appTasks, OhosAppContext, OhosPluginId } from '@ohos/hvigor-ohos-plugin';
import { getNode, hvigor, HvigorTaskContext, TaskInput, TaskOutput } from "@ohos/hvigor";
import fse from "fs-extra";
import path from "path";

const currentNode = getNode(__filename);
hvigor.nodesEvaluated(() => {
  const context = currentNode.getContext(OhosPluginId.OHOS_APP_PLUGIN) as OhosAppContext;
  const outputFilePath = path.resolve(context.getBuildRootPath(), 'testOutput.txt');
  // Add the path of a file as the input condition for an incremental build task.
  const inputFilePath = path.resolve(context.getProjectPath(), 'testInput.txt');
  // Register a file generation task and enable incremental processing for this task.
  currentNode.registerTask({
    name: "testTask",
    run(taskContext: HvigorTaskContext): void | Promise<void> {
      const parentDir = path.dirname(outputFilePath);
      fse.ensureDirSync(parentDir); // Ensure that the parent directory exists.
      fse.ensureFileSync(outputFilePath);
      fse.writeFileSync(outputFilePath, context.getProjectName());
      return undefined;
    },
    input(input: TaskInput): void {
      input.property('projectName', context.getProjectName());
      if (fse.existsSync(inputFilePath)) {
        input.files([inputFilePath, ]);
      }
    },
    async output(output: TaskOutput): Promise<void> {
      output.files([outputFilePath,]);
    },
    postDependencies: ['assembleApp']
  })
})

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[]         /* Custom plugin to extend the functionality of Hvigor. */
}

Add dependencies to hvigor-config.json5 as follows:

// hvigor-config.json5
"dependencies": {
  "fs-extra": "11.2.0",
  "@types/fs-extra": "9.0.13"
},

Task

Represents the external object of HvigorTask. You can use this object to access task properties and call API functions provided by the task.

[h2]Modules to Import

import { Task } from '@ohos/hvigor';

[h2]getName

getName: () => string

Obtains the task name.

Returns

Type

Description

String

Name of the task to obtain.

Example

// Project-level hvigorfile.ts file
import { appTasks } from '@ohos/hvigor-ohos-plugin';
import { hvigor, Task } from '@ohos/hvigor';

hvigor.nodesEvaluated(() => {
  const rootNode = hvigor.getRootNode();
  const assembleAppTask: Task | undefined = rootNode.getTaskByName('assembleApp');
  if (assembleAppTask) {
    const taskName = assembleAppTask.getName();
    console.log(`taskName: ${taskName}`);
  }
});

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[]         /* Custom plugin to extend the functionality of Hvigor. */
}

[h2]getDependencies

getDependencies: () => string[]

Obtains the dependencies, on which this task depends.

Returns

Type

Description

string[]

Dependencies to obtain.

Example

// Project-level hvigorfile.ts file
import { appTasks } from '@ohos/hvigor-ohos-plugin';
import { hvigor, Task } from '@ohos/hvigor';

hvigor.nodesEvaluated(() => {
  const rootNode = hvigor.getRootNode();
  const assembleAppTask: Task | undefined = rootNode.getTaskByName('assembleApp');
  if (assembleAppTask) {
    const taskDependencies = assembleAppTask.getDependencies();
    console.log(`Task Dependencies: ${taskDependencies}`);
  }
});

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[]         /* Custom plugin to extend the functionality of Hvigor. */
}

[h2]setEnable

setEnable: (enable: boolean) => void

Sets the task status. Disabling a task skips the execution of the task without affecting the task dependency relationships. When a task is registered, it is enabled by default.

Parameters

Name

Type

Mandatory

Description

enable

Boolean

Yes

Whether to enable the task. The value true means to enable the task, and the value false means the opposite.

Example

// Project-level hvigorfile.ts file
import { appTasks, OhosHapContext, OhosPluginId, Target } from '@ohos/hvigor-ohos-plugin';
import { hvigor, HvigorNode } from '@ohos/hvigor';
hvigor.nodesEvaluated(() => {
  const rootNode = hvigor.getRootNode();
  rootNode.subNodes((node: HvigorNode) => {
    // Obtain the context of the HAP module.
    const hapContext = node.getContext(OhosPluginId.OHOS_HAP_PLUGIN) as OhosHapContext;
    const moduleName = hapContext?.getModuleName();
    hapContext?.targets((target: Target) => {
      // Disable the task.
      node.getTaskByName(`${target.getTargetName()}@SignHap`)?.setEnable(false);
    });
  });
});
export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[]         /* Custom plugin to extend the functionality of Hvigor. */
}

[h2]beforeRun

beforeRun: (fn: Function) => void

Adds a hook function to run before this task. Hook functions are stored in a stack and follow the first-in, last-out (FILO) principle, which allows the last function added to be executed first.

Parameters

Name

Type

Mandatory

Description

fn

Function

Yes

Hook function to add.

Example

// Project-level hvigorfile.ts file
import { appTasks } from '@ohos/hvigor-ohos-plugin';
import { hvigor, Task } from '@ohos/hvigor';

hvigor.nodesEvaluated(() => {
  const rootNode = hvigor.getRootNode();
  const assembleAppTask: Task | undefined = rootNode.getTaskByName('assembleApp');
  if (assembleAppTask) {
    // Hook function to run before this task
    assembleAppTask.beforeRun(() => {
      console.log('Before Task: assembleApp');
    });
  }
});

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[]         /* Custom plugin to extend the functionality of Hvigor. */
}

[h2]afterRun

afterRun: (fn: Function) => void

Adds a hook function to run after this task. Hook functions are stored in a heap and follow the FIFO principle, which allows the first function added to be executed first.

Parameters

Name

Type

Mandatory

Description

fn

Function

Yes

Hook function to add.

Example

// Project-level hvigorfile.ts file
import { appTasks } from '@ohos/hvigor-ohos-plugin';
import { hvigor, Task } from '@ohos/hvigor';

hvigor.nodesEvaluated(() => {
  const rootNode = hvigor.getRootNode();
  const assembleAppTask: Task | undefined = rootNode.getTaskByName('assembleApp');
  if (assembleAppTask) {
    // Hook function to run after this task
    assembleAppTask.afterRun(() => {
      console.log('After Task: assembleApp');
    });
  }
});

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[]         /* Custom plugin to extend the functionality of Hvigor. */
}

SdkDetails

Represents the information of the SDK used by the app project. Before calling this API, you can use the getSdkDetails method of OhosAppContext to obtain the object.

[h2]Modules to Import

import { SdkDetails } from '@ohos/hvigor-ohos-plugin';

[h2]getSdkDir

getSdkDir: () => string

Obtains the SDK directory.

Since: Hvigor 6.0.4

Returns

Type

Description

String

SDK directory to obtain.

Sample code for the project-level hvigorfile.ts file:

// Project-level hvigorfile.ts file
import { appTasks, OhosAppContext, OhosPluginId, SdkDetails } from '@ohos/hvigor-ohos-plugin';
import { hvigor, HvigorNode, HvigorPlugin } from '@ohos/hvigor';

export function customPlugin(): HvigorPlugin {
  return {
    pluginId: 'customPlugin',
    context() {
      return {
        data: 'customPlugin xxx'
      };
    },
    async apply(currentNode: HvigorNode): Promise<void> {
      hvigor.afterNodeEvaluate(node => {
        const appContext = node.getContext(OhosPluginId.OHOS_APP_PLUGIN) as OhosAppContext;
        if (appContext) {
          let sdk:SdkDetails = appContext.getSdkDetails();
          console.log(sdk?.getSdkDir())
        }
      });
    }
  };
}

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[customPlugin()]         /* Custom plugin to extend the functionality of Hvigor. */
}

[h2]isOhos

isOhos: () => boolean

Determines whether the OpenHarmony SDK is in use.

Since: Hvigor 6.0.4

Returns

Type

Description

Boolean

Whether the OpenHarmony SDK is in use.

Sample code for the project-level hvigorfile.ts file:

// Project-level hvigorfile.ts file
import { appTasks } from '@ohos/hvigor-ohos-plugin';
import { OhosAppContext, OhosPluginId, SdkDetails } from '@ohos/hvigor-ohos-plugin';
import { hvigor, HvigorNode, HvigorPlugin } from '@ohos/hvigor';

export function customPlugin(): HvigorPlugin {
  return {
    pluginId: 'customPlugin',
    context() {
      return {
        data: 'customPlugin xxx'
      };
    },
    async apply(currentNode: HvigorNode): Promise<void> {
      hvigor.afterNodeEvaluate(node => {
        const appContext = node.getContext(OhosPluginId.OHOS_APP_PLUGIN) as OhosAppContext;
        if (appContext) {
          let sdk:SdkDetails = appContext.getSdkDetails();
          console.log(sdk?.isOhos())
        }
      });
    }
  };
}

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[customPlugin()]         /* Custom plugin to extend the functionality of Hvigor. */
}

[h2]getSdkVersion

getSdkVersion: () => number

Obtains the SDK version.

Since: Hvigor 6.0.4

Returns

Type

Description

Number

SDK version.

Sample code for the project-level hvigorfile.ts file:

// Project-level hvigorfile.ts file
import { appTasks } from '@ohos/hvigor-ohos-plugin';
import { OhosAppContext, OhosHapContext, OhosPluginId, SdkDetails } from '@ohos/hvigor-ohos-plugin';
import { hvigor, HvigorNode, HvigorPlugin } from '@ohos/hvigor';

export function customPlugin(): HvigorPlugin {
  return {
    pluginId: 'customPlugin',
    context() {
      return {
        data: 'customPlugin xxx'
      };
    },
    async apply(currentNode: HvigorNode): Promise<void> {
      hvigor.afterNodeEvaluate(node => {
        const appContext = node.getContext(OhosPluginId.OHOS_APP_PLUGIN) as OhosAppContext;
        if (appContext) {
          let sdk:SdkDetails = appContext.getSdkDetails();
          console.log(sdk?.getSdkVersion())
        }
      });
    }
  };
}

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[customPlugin()]         /* Custom plugin to extend the functionality of Hvigor. */
}

[h2]getEtsComponentVersion

getEtsComponentVersion: () => string

Obtains the version of the ETS component in the SDK (component located in the DevEco Studio installation directory/sdk/default/openharmony/ets directory).

Since: Hvigor 6.0.4

Returns

Type

Description

String

Version number to obtain.

Sample code for the project-level hvigorfile.ts file:

// Project-level hvigorfile.ts file
import { appTasks } from '@ohos/hvigor-ohos-plugin';
import { OhosAppContext, OhosPluginId, SdkDetails } from '@ohos/hvigor-ohos-plugin';
import { hvigor, HvigorNode, HvigorPlugin } from '@ohos/hvigor';

export function customPlugin(): HvigorPlugin {
  return {
    pluginId: 'customPlugin',
    context() {
      return {
        data: 'customPlugin xxx'
      };
    },
    async apply(currentNode: HvigorNode): Promise<void> {
      hvigor.afterNodeEvaluate(node => {
        const appContext = node.getContext(OhosPluginId.OHOS_APP_PLUGIN) as OhosAppContext;
        if (appContext) {
          let sdk:SdkDetails = appContext.getSdkDetails();
          console.log(sdk?.getEtsComponentVersion())
        }
      });
    }
  };
}

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[customPlugin()]         /* Custom plugin to extend the functionality of Hvigor. */
}

[h2]getEtsComponentReleaseType

getEtsComponentReleaseType: () => string

Obtains the release type of the ETS component in the SDK (component located in the DevEco Studio installation directory/sdk/default/openharmony/ets directory).

Since: Hvigor 6.0.4

Returns

Type

Description

String

Release type to obtain.

Sample code for the project-level hvigorfile.ts file:

// Project-level hvigorfile.ts file
import { appTasks } from '@ohos/hvigor-ohos-plugin';
import { OhosAppContext, OhosPluginId, SdkDetails } from '@ohos/hvigor-ohos-plugin';
import { hvigor, HvigorNode, HvigorPlugin } from '@ohos/hvigor';

export function customPlugin(): HvigorPlugin {
  return {
    pluginId: 'customPlugin',
    context() {
      return {
        data: 'customPlugin xxx'
      };
    },
    async apply(currentNode: HvigorNode): Promise<void> {
      hvigor.afterNodeEvaluate(node => {
        const appContext = node.getContext(OhosPluginId.OHOS_APP_PLUGIN) as OhosAppContext;
        if (appContext) {
          let sdk:SdkDetails = appContext.getSdkDetails();
          console.log(sdk?.getEtsComponentReleaseType())
        }
      });
    }
  };
}

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[customPlugin()]         /* Custom plugin to extend the functionality of Hvigor. */
}

NormalizedFile

Represents the file class in the Hvigor API. You can use this object to perform basic file operations.

[h2]filePath

filePath: string

Represents the path of the current object.

Since: Hvigor 4.3.0

Example

// Project-level hvigorfile.ts file
import { appTasks } from '@ohos/hvigor-ohos-plugin';
import { hvigor } from '@ohos/hvigor';

hvigor.nodesEvaluated(() => {
  const rootNode = hvigor.getRootNode();
  const moduleNormalizedFile = rootNode.nodeDir;
  console.log(`Module Normalized File Path: ${moduleNormalizedFile.filePath}`);
})

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[]         /* Custom plugin to extend the functionality of Hvigor. */
}

[h2]getPath

getPath: () => string

Obtains the path of the current object.

Since: Hvigor 4.3.0

Returns

Type

Description

String

Path of the current object.

Example

// Project-level hvigorfile.ts file
import { appTasks } from '@ohos/hvigor-ohos-plugin';
import { hvigor } from '@ohos/hvigor';

hvigor.nodesEvaluated(() => {
  const rootNode = hvigor.getRootNode();
  const moduleNormalizedFile = rootNode.nodeDir;
  console.log(`Module Normalized File Path: ${moduleNormalizedFile.getPath()}`);
})

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[]         /* Custom plugin to extend the functionality of Hvigor. */
}

[h2]file

file: (_path: string) => NormalizedFile

Chains and appends the specified path to the existing directory path to obtain a NormalizedFile object.

Since: Hvigor 4.3.0

Parameters

Name

Type

Mandatory

Description

_path

String

Yes

Path to be appended.

Returns

Type

Description

NormalizedFile

NormalizedFile object obtained by chaining paths based on the existing NormalizedFile object.

Example

// Project-level hvigorfile.ts file
import { appTasks } from '@ohos/hvigor-ohos-plugin';
import { hvigor } from '@ohos/hvigor';

hvigor.nodesEvaluated(() => {
  const rootNode = hvigor.getRootNode();
  const moduleNormalizedFile = rootNode.nodeDir;
  const buildProfileNormalizedFile = moduleNormalizedFile.file('build-profile.json5');
  console.log(`buildProfile File Path: ${buildProfileNormalizedFile.getPath()}`);
})

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[]         /* Custom plugin to extend the functionality of Hvigor. */
}

[h2]asFileList

asFileList: () => NormalizedFile[]

Obtains all files and directories recursively contained within the NormalizedFile object, including the object itself.

Since: Hvigor 4.3.0

Returns

Type

Description

NormalizedFile[]

Files and directories recursively contained within the NormalizedFile object, including the object itself.

Currently, you can only obtain the NormalizedFile object of the root path of a node via node.nodeDir or node.getNodeDir(). Then, by using the NormalizedFile.file(_path: string) method to concatenate subsequent paths, you can obtain a new NormalizedFile object. The following provides sample code for the project-level hvigorfile.ts file:

import { appTasks } from '@ohos/hvigor-ohos-plugin';
// Import dependencies.
import { HvigorPlugin, HvigorNode} from '@ohos/hvigor';
// Implement a custom plugin.
function customPlugin(): HvigorPlugin {
  return {
    pluginId: 'customPlugin',
    apply(node: HvigorNode) {
      appTask(node);
    }
  }
}
function appTask(currentNode: HvigorNode) {
  // Project-level node
  currentNode.subNodes((node: HvigorNode) => {
    // Module-level node
    // Obtain the NormalizedFile object of the root path of the node via node.nodeDir or node.getNodeDir().
    const moduleNormalizedFile = node.nodeDir;
    // Use NormalizedFile.file() to concatenate subsequent paths and generate a new NormalizedFile object.
    // Generate the NormalizedFile object of the build-Profile.json5 file for the module.
    const buildProfileNormalizedFile = moduleNormalizedFile.file('build-profile.json5');
  })
}
export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[
    customPlugin()  // Apply the custom plugin.
  ]         /* Custom plugin to extend the functionality of Hvigor. */
}

FileUtil

Represents the file utility class that supports basic file operations.

[h2]Modules to Import

import { FileUtil } from '@ohos/hvigor';

[h2]exist

exist: (filePath: string) => boolean

Checks whether a file path exists.

Since: Hvigor 4.3.0

Parameters

Name

Type

Mandatory

Description

filePath

String

Yes

File path.

Returns

Type

Description

Boolean

true: The file path exists. false: The file path does not exist.

Example

// Project-level hvigorfile.ts file
import { appTasks, OhosPluginId, OhosAppContext } from '@ohos/hvigor-ohos-plugin';
import { hvigor, FileUtil, getNode } from '@ohos/hvigor';
import path from "path";

const currentNode = getNode(__filename);
hvigor.nodesEvaluated(() => {
  const context = currentNode.getContext(OhosPluginId.OHOS_APP_PLUGIN) as OhosAppContext;
  const testFilePath = path.resolve(context.getProjectPath(), 'test.txt');
  if (FileUtil.exist(testFilePath)) {
    console.log(`File exists: ${testFilePath}`);
  } else {
    console.log(`File doesn't exist: ${testFilePath}`);
  }
})

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[]         /* Custom plugin to extend the functionality of Hvigor. */
}

[h2]isDictionary

isDictionary: (file: string | NormalizedFile) => boolean

Checks whether a file path or NormalizedFile object is a directory.

Since: Hvigor 4.3.0

Parameters

Name

Type

Mandatory

Description

file

String | NormalizedFile

Yes

File path or NormalizedFile object.

Returns

Type

Description

Boolean

true: The target is a directory. false: The target is not a directory.

Example

// Project-level hvigorfile.ts file
import { appTasks, OhosPluginId, OhosAppContext } from '@ohos/hvigor-ohos-plugin';
import { hvigor, FileUtil, getNode } from '@ohos/hvigor';
import path from "path";

const currentNode = getNode(__filename);
hvigor.nodesEvaluated(() => {
  const context = currentNode.getContext(OhosPluginId.OHOS_APP_PLUGIN) as OhosAppContext;
  const testFilePath = path.resolve(context.getProjectPath(), 'test.txt');
  FileUtil.ensureFileSync(testFilePath);
  if (FileUtil.isDictionary(testFilePath)) {
    console.log(`It is a directory: ${testFilePath}`);
  } else {
    console.log(`It is not a directory: ${testFilePath}`);
  }
})

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[]         /* Custom plugin to extend the functionality of Hvigor. */
}

[h2]isFile

isFile: (file: string | NormalizedFile) => boolean

Checks whether a file path or NormalizedFile object is a file.

Since: Hvigor 4.3.0

Parameters

Name

Type

Mandatory

Description

file

String | NormalizedFile

Yes

File path or NormalizedFile object.

Returns

Type

Description

Boolean

true: The target is a file. false: The target is not a file.

Example

// Project-level hvigorfile.ts file
import { appTasks, OhosPluginId, OhosAppContext } from '@ohos/hvigor-ohos-plugin';
import { hvigor, FileUtil, getNode } from '@ohos/hvigor';
import path from "path";

const currentNode = getNode(__filename);
hvigor.nodesEvaluated(() => {
  const context = currentNode.getContext(OhosPluginId.OHOS_APP_PLUGIN) as OhosAppContext;
  const testFilePath = path.resolve(context.getProjectPath(), 'test.txt');
  FileUtil.ensureFileSync(testFilePath);
  if (FileUtil.isFile(testFilePath)) {
    console.log(`It is a file: ${testFilePath}`);
  } else {
    console.log(`It is not a file: ${testFilePath}`);
  }
})

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[]         /* Custom plugin to extend the functionality of Hvigor. */
}

[h2]ensureDirSync

ensureDirSync: (dirPath: string) => void

Ensures that the directory exists; creates it if it does not exist.

Since: Hvigor 4.3.0

Parameters

Name

Type

Mandatory

Description

dirPath

String

Yes

Destination directory path.

Example

// Project-level hvigorfile.ts file
import { appTasks, OhosPluginId, OhosAppContext } from '@ohos/hvigor-ohos-plugin';
import { hvigor, FileUtil, getNode } from '@ohos/hvigor';
import path from "path";

const currentNode = getNode(__filename);
hvigor.nodesEvaluated(() => {
  const context = currentNode.getContext(OhosPluginId.OHOS_APP_PLUGIN) as OhosAppContext;
  FileUtil.ensureDirSync(path.dirname(context.getBuildRootPath()));
})
export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[]         /* Custom plugin to extend the functionality of Hvigor. */
}

[h2]ensureFileSync

ensureFileSync: (filePath: string) => void

Ensures that the file exists; creates it if it does not exist.

Since: Hvigor 4.3.0

Parameters

Name

Type

Mandatory

Description

filePath

String

Yes

Destination file path.

Example

// Project-level hvigorfile.ts file
import { appTasks, OhosPluginId, OhosAppContext } from '@ohos/hvigor-ohos-plugin';
import { hvigor, FileUtil, getNode } from '@ohos/hvigor';
import path from "path";

const currentNode = getNode(__filename);
hvigor.nodesEvaluated(() => {
  const context = currentNode.getContext(OhosPluginId.OHOS_APP_PLUGIN) as OhosAppContext;
  const testFilePath = path.resolve(context.getProjectPath(), 'test.txt');
  FileUtil.ensureFileSync(testFilePath);
})

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[]         /* Custom plugin to extend the functionality of Hvigor. */
}

[h2]readJson5

readJson5: (file: string | NormalizedFile) => JSON

Reads a JSON5 file synchronously.

Since: Hvigor 4.3.0

Parameters

Name

Type

Mandatory

Description

file

String | NormalizedFile

Yes

JSON5 file path or NormalizedFile object.

Returns

Type

Description

JSON

Read JSON data.

Example

// Project-level hvigorfile.ts file
import { appTasks, OhosPluginId, OhosAppContext } from '@ohos/hvigor-ohos-plugin';
import { hvigor, FileUtil, getNode } from '@ohos/hvigor';
import path from "path";

const currentNode = getNode(__filename);
hvigor.nodesEvaluated(() => {
  const context = currentNode.getContext(OhosPluginId.OHOS_APP_PLUGIN) as OhosAppContext;
  const json5FilePath = path.resolve(context.getProjectPath(), 'testJson.json5');
  FileUtil.ensureFileSync(json5FilePath);
  FileUtil.writeFileSync(json5FilePath, JSON.stringify(context.getAppJsonOpt()));
  const jsonContent = FileUtil.readJson5(json5FilePath);
  console.log(`Read JSON5 content: ${JSON.stringify(jsonContent, null, 2)}`);
})

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[]         /* Custom plugin to extend the functionality of Hvigor. */
}

[h2]readFileSync

readFileSync: (file: string | NormalizedFile) => Buffer

Reads a file synchronously.

Since: Hvigor 4.3.0

Parameters

Name

Type

Mandatory

Description

file

String | NormalizedFile

Yes

File path or NormalizedFile object.

Returns

Type

Description

Buffer

Read buffer data.

Example

// Project-level hvigorfile.ts file
import { appTasks, OhosPluginId, OhosAppContext } from '@ohos/hvigor-ohos-plugin';
import { hvigor, FileUtil, getNode } from '@ohos/hvigor';
import path from "path";

const currentNode = getNode(__filename);
hvigor.nodesEvaluated(() => {
  const context = currentNode.getContext(OhosPluginId.OHOS_APP_PLUGIN) as OhosAppContext;
  const json5FilePath = path.resolve(context.getProjectPath(), 'testJson.json5');
  FileUtil.ensureFileSync(json5FilePath);
  FileUtil.writeFileSync(json5FilePath, JSON.stringify(context.getAppJsonOpt()));
  const content = FileUtil.readFileSync(json5FilePath);
  console.log(`Content of ${json5FilePath}: ${content}`);
})

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[]         /* Custom plugin to extend the functionality of Hvigor. */
}

[h2]readFile

readFile: (file: string | NormalizedFile) => Promise<Buffer>

Reads a file asynchronously.

Since: Hvigor 4.3.0

Parameters

Name

Type

Mandatory

Description

file

String | NormalizedFile

Yes

File path or NormalizedFile object.

Returns

Type

Description

Promise

Promise<Buffer>

Example

// Project-level hvigorfile.ts file
import { appTasks, OhosPluginId, OhosAppContext } from '@ohos/hvigor-ohos-plugin';
import { hvigor, FileUtil, getNode } from '@ohos/hvigor';
import path from "path";

const currentNode = getNode(__filename);
hvigor.nodesEvaluated(async () => {
  const context = currentNode.getContext(OhosPluginId.OHOS_APP_PLUGIN) as OhosAppContext;
  const json5FilePath = path.resolve(context.getProjectPath(), 'testJson.json5');
  FileUtil.ensureFileSync(json5FilePath);
  FileUtil.writeFileSync(json5FilePath, JSON.stringify(context.getAppJsonOpt()));
  const content = await FileUtil.readFile(json5FilePath);
  console.log(content.toString());
})

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[]         /* Custom plugin to extend the functionality of Hvigor. */
}

[h2]writeFileSync

writeFileSync: (file: string | NormalizedFile, content: any) => void

Writes data to a file synchronously.

Since: Hvigor 4.3.0

Parameters

Name

Type

Mandatory

Description

file

String | NormalizedFile

Yes

File path or NormalizedFile object.

content

Any

Yes

Data to be written to the file.

Example

// Project-level hvigorfile.ts file
import { appTasks, OhosPluginId, OhosAppContext } from '@ohos/hvigor-ohos-plugin';
import { hvigor, FileUtil, getNode } from '@ohos/hvigor';
import path from "path";

const currentNode = getNode(__filename);
hvigor.nodesEvaluated(() => {
  const context = currentNode.getContext(OhosPluginId.OHOS_APP_PLUGIN) as OhosAppContext;
  const json5FilePath = path.resolve(context.getProjectPath(), 'testJson.json5');
  FileUtil.ensureFileSync(json5FilePath);
  FileUtil.writeFileSync(json5FilePath, JSON.stringify(context.getAppJsonOpt()));
  const jsonContent = FileUtil.readJson5(json5FilePath);
  console.log(`Read JSON5 content: ${JSON.stringify(jsonContent, null, 2)}`);
})

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[]         /* Custom plugin to extend the functionality of Hvigor. */
}

[h2]writeFile

writeFile: (file: string | NormalizedFile, content: any) => Promise<void>

Writes data to a file asynchronously.

Since: Hvigor 4.3.0

Parameters

Name

Type

Mandatory

Description

file

String | NormalizedFile

Yes

File path or NormalizedFile object.

content

Any

Yes

Data to be written to the file.

Returns

Type

Description

Promise

Promise<void>

Example

// Project-level hvigorfile.ts file
import { appTasks, OhosPluginId, OhosAppContext } from '@ohos/hvigor-ohos-plugin';
import { hvigor, FileUtil, getNode } from '@ohos/hvigor';
import path from "path";

const currentNode = getNode(__filename);
hvigor.nodesEvaluated(() => {
  const context = currentNode.getContext(OhosPluginId.OHOS_APP_PLUGIN) as OhosAppContext;
  const json5FilePath = path.resolve(context.getProjectPath(), 'testJson.json5');
  FileUtil.ensureFileSync(json5FilePath);
  FileUtil.writeFile(json5FilePath, JSON.stringify(context.getAppJsonOpt()));
})

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[]         /* Custom plugin to extend the functionality of Hvigor. */
}

[h2]copyFileSync

copyFileSync: (file: string | NormalizedFile, dest: string) => void

Copies a file synchronously.

Since: Hvigor 4.3.0

Parameters

Name

Type

Mandatory

Description

file

String | NormalizedFile

Yes

File path or NormalizedFile object.

dest

String

Yes

Destination file path.

Example

// Project-level hvigorfile.ts file
import { appTasks, OhosPluginId, OhosAppContext } from '@ohos/hvigor-ohos-plugin';
import { hvigor, FileUtil, getNode } from '@ohos/hvigor';

const currentNode = getNode(__filename);
hvigor.nodesEvaluated(() => {
  const context = currentNode.getContext(OhosPluginId.OHOS_APP_PLUGIN) as OhosAppContext;
  const json5FilePath = FileUtil.pathResolve(context.getProjectPath(), 'testJson.json5');
  FileUtil.ensureFileSync(json5FilePath);
  FileUtil.writeFileSync(json5FilePath, JSON.stringify(context.getAppJsonOpt()));
  const copyFilePath = FileUtil.pathResolve(context.getProjectPath(), 'testJson_copy.json5');
  FileUtil.copyFileSync(json5FilePath, copyFilePath);
})

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[]         /* Custom plugin to extend the functionality of Hvigor. */
}

[h2]copyFile

copyFile: (file: string | NormalizedFile, dest: string) => Promise<void>

Copies a file asynchronously.

Since: Hvigor 4.3.0

Parameters

Name

Type

Mandatory

Description

file

String | NormalizedFile

Yes

File path or NormalizedFile object.

dest

String

Yes

Destination file path.

Returns

Type

Description

Promise

Promise<void>

Example

// Project-level hvigorfile.ts file
import { appTasks, OhosPluginId, OhosAppContext } from '@ohos/hvigor-ohos-plugin';
import { hvigor, FileUtil, getNode } from '@ohos/hvigor';

const currentNode = getNode(__filename);
hvigor.nodesEvaluated(() => {
  const context = currentNode.getContext(OhosPluginId.OHOS_APP_PLUGIN) as OhosAppContext;
  const json5FilePath = FileUtil.pathResolve(context.getProjectPath(), 'testJson.json5');
  FileUtil.ensureFileSync(json5FilePath);
  FileUtil.writeFileSync(json5FilePath, JSON.stringify(context.getAppJsonOpt()));
  const copyFilePath = FileUtil.pathResolve(context.getProjectPath(), 'testJson_copy.json5');
  FileUtil.copyFile(json5FilePath, copyFilePath);
})

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[]         /* Custom plugin to extend the functionality of Hvigor. */
}

[h2]pathResolve

pathResolve: (...paths: string[]) => string

Resolves paths to an absolute path.

Since: Hvigor 4.3.0

Parameters

Name

Type

Mandatory

Description

...paths

string[]

Yes

Array of file paths.

Returns

Type

Description

String

Path obtained after resolution.

Example

// Project-level hvigorfile.ts file
import { appTasks, OhosPluginId, OhosAppContext } from '@ohos/hvigor-ohos-plugin';
import { hvigor, FileUtil, getNode } from '@ohos/hvigor';

const currentNode = getNode(__filename);
hvigor.nodesEvaluated(() => {
  const context = currentNode.getContext(OhosPluginId.OHOS_APP_PLUGIN) as OhosAppContext;
  const json5FilePath = FileUtil.pathResolve(context.getProjectPath(), 'testJson.json5');
  FileUtil.ensureFileSync(json5FilePath);
  FileUtil.writeFile(json5FilePath, JSON.stringify(context.getAppJsonOpt()));
})

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[]         /* Custom plugin to extend the functionality of Hvigor. */
}

submitWorker

submitWorker(node: HvigorNode, taskName: string, workPath: string, workerOption: WorkerOption): TCB

Submits a worker to the thread pool for execution. The worker must belong to a specific task, indicating that the task is not yet completed. The main thread can continue executing other tasks, while other tasks dependent on this one will still wait in the queue.

Since: Hvigor 6.0.4

Parameters

Name

Type

Mandatory

Description

node

HvigorNode

Yes

Node of the task to which the worker belongs.

taskName

String

Yes

Name of the task that submits the worker to the thread pool.

workPath

String

Yes

File path of the worker to be executed, to which the function name can be appended, for example, D:/xx/a.js/run, indicating the run method of a.js.

workerOption

WorkerOption

Yes

Worker configuration.

Returns

Type

Description

TCB

Status of the submitted worker.

Example: submitting a worker to the thread pool in the custom task of the HAP module

import { hapTasks } from '@ohos/hvigor-ohos-plugin';
import { HvigorNode, HvigorPlugin, submitWorker } from "@ohos/hvigor";
import path from "path";

// Implement a custom plugin.
function customPlugin(): HvigorPlugin {
  return {
    pluginId: 'customPlugin',
    apply(node: HvigorNode) {
      // Plugin code.
      node.registerTask({
        name: 'customTask',
        run() {
          submitWorker(node, this.name, path.join(__dirname, 'wait-job.js', 'wait'), {callback: () => {
            console.log('submit Worker callback');
          }});
        },
        dependencies: ['default@PreBuild'],
        postDependencies: ['assembleHap'],
      });
    }
  }
}

export default {
  system: hapTasks /* Built-in plugin of Hvigor. It cannot be modified. */,
  plugins: [customPlugin()] /* Custom plugin to extend the functionality of Hvigor. */,  
};

The content of wait-job.js is as follows. This file is in the same directory as hvigorfile.ts.

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

async function wait() {
    console.log('Waiting for 10 seconds...');
    await sleep(10000);
    console.log('Finished, exiting the program');
}

exports.wait = wait;

WorkerOption

Configures options for the worker submitted to the thread pool. For submission methods, see submitWorker.

Since: Hvigor 6.0.4

Member

Declaration

Description

workInput

workInput?: unknown;

Input value for the worker.

priority

priority?: Priority;

Priority of the worker.

targetWorkers

targetWorkers?: number[];

IDs of the worker threads for execution.

callback

callback?: Function;

Callback function triggered after the execution is complete.

callbackInput

callbackInput?: unknown[];

Input parameters of the callback function.

useReturnVal

useReturnVal?: boolean;

Whether the callback function uses the value returned upon worker execution completion as the input. The priority of this option is higher than that of callbackInput.

Priority

Enumerates the priorities of worker execution.

Since: Hvigor 6.0.4

Member

Description

FIRST

The priorities decrease from top to bottom.

HEAVY

MEDIUM

LIGHT

LAST

TCB

Indicates the status returned after a worker is submitted to the thread pool. For submission methods, see submitWorker.

Since: Hvigor 6.0.4

Member

Declaration

Description

getId

getId(): string;

Obtains the task control block (TCB) ID.

getWorkerId

getWorkerId(): number | undefined;

Obtains the worker ID.

getSubmitTime

getSubmitTime(): number;

Obtains the submission time.

getStartTime

getStartTime(): number | undefined;

Obtains the execution start time.

getEndTime

getEndTime(): number | undefined;

Obtains the execution end time.

getState

getState(): TaskState;

Obtains the worker status.

getPriority

getPriority(): Priority;

Obtains the worker priority.

getCallback

getCallback(): Function;

Obtains the callback function.

getCallbackInput

getCallbackInput(): unknown[];

Obtains the input of the callback function.

getTaskPath

getTaskPath(): string;

Obtains the task path.

getTaskName

getTaskName(): string;

Obtains the task name.

getTaskCompletePath

getTaskCompletePath(): string;

Obtains the full task path, including the task path and task name.

useReturnVal

useReturnVal(): boolean;

Specifies whether the callback function uses the value returned upon worker execution completion as the input.