SoFunction
Updated on 2025-03-04

How to dynamically generate code in Hongmeng development Hvigor plug-in

Hvigor allows developers to implement their own plugins, which can define their own build logic and share with others. Hvigor mainly provides two ways to implement plug-ins: development plug-ins based on hvigorfile scripts, and development based on typescript projects. The following is an introduction to the development plug-in based on hvigorfile scripts.

Developed based on hvigorfile scripts

Based on script development, its advantage is that it can achieve rapid development and can directly edit projects or modules to write plug-in code. The disadvantage is that it cannot be conveniently reused and shared distribution of plug-in code in multiple projects.

  • Import module dependencies.
// Import interfaceimport { HvigorPlugin, HvigorNode } from '@ohos/hvigor'
  • Write plugin code.
    Define the plug-in method in it to implement the HvigorPlugin interface.
// Implement custom plug-insfunction customPlugin(): HvigorPlugin {
    return {
        pluginId: 'customPlugin',
        apply(node: HvigorNode) {
            // Plug-in body            ('hello customPlugin!');
        }
    }
}
  • Use plugins in export declarations.
export default {
    system: appTasks,
    plugins:[
        customPlugin()  // Apply custom Plugin    ]
}

Dynamically generate navigation anti-obfuscated files using hvigorfile plugin

When we use navigation system routing tables, every time we add a new page, we need to configure the release environment to prevent obfuscation. If you place these pages in a fixed directory, it is contrary to our modular design. If you use a fixed prefix or suffix to name it, it always feels a bit redundant and add it manually one by one. Although it conforms to our code specification design, it is a bit cumbersome. Is there a more convenient way to deal with this obfuscated configuration?

In fact, we can write a hvigorfilew plugin to automatically generate obfuscation configuration files. We customize a HvigorPlugin task, read the routerMap field in the module.json5 file through the OhosHapContext object, and get the name of the system routing table, and then read the routing table in the profile directory. Parses the json file memory and writes the page path to an obfuscation file. This way, every time you compile, an anti-obfuscation file is automatically generated. We only need to introduce this file. The example is as follows

import { hapTasks, OhosHapContext, OhosPluginId } from '@ohos/hvigor-ohos-plugin'
import { HvigorPlugin, HvigorNode, FileUtil } from '@ohos/hvigor'
function parseRouterMap(): HvigorPlugin {
  return {
    pluginId: 'parseRouterMap',
    apply(node: HvigorNode) {
      const hapCtx = (OhosPluginId.OHOS_HAP_PLUGIN) as OhosHapContext
      const moduleJson = ()
      const routerMapName = moduleJson['module']['routerMap'].split(':')[1]
      const dir = ()
      const srcFile = (dir, 'src', 'main', 'resources', 'base', 'profile', `${routerMapName}.json`)
      const json = FileUtil.readJson5(srcFile)
      const routerRuleFile = (dir, '')
      (routerRuleFile)
      const routerMapArray = json['routerMap']
      let rules = '-keep-file-name\n'
      for (const element of routerMapArray) {
        const pageSourceFile = element['pageSourceFile']
        const path = (0, ('.'))
        rules += `${path}\n`
      }
      (routerRuleFile, rules)
    }
  }
}
export default {
  system: hapTasks,
  plugins:[parseRouterMap()]
}

After compilation, an anti-obfuscation file will be generated in the entry directory, just import this file.

Dynamically generate navigation page enumeration name using hvigorfile plugin

When our navigation push jumps to a new page, we have to define the page name in the system routing table in advance, because when the name used is different from the name defined in the system routing table, the jump page will be white. With the previous experience, we can also dynamically generate an ets file and automatically generate an enumeration of the page names in the system routing table, so that we don’t have to configure the system routing table every time, but we will just copy the name. For example, our system routing table is like this

{
  "routerMap": [
    {
      "name": "dialog",
      "pageSourceFile": "src/main/ets/pages/dialog/",
      "buildFunction": "dialogBuilder"
    },
    {
      "name": "web",
      "pageSourceFile": "src/main/ets/pages/web/",
      "buildFunction": "webBuilder"
    },
    {
      "name": "login",
      "pageSourceFile": "src/main/ets/pages/login/",
      "buildFunction": "loginBuilder"
    }
  ]
}

We now implement a hvigorfile plugin to parse the name field in the system routing table and generate the corresponding enumeration value. The example is as follows

import { hapTasks, OhosHapContext, OhosPluginId } from '@ohos/hvigor-ohos-plugin'
import { HvigorPlugin, HvigorNode, FileUtil } from '@ohos/hvigor'
function parseRouterMap(): HvigorPlugin {
  return {
    pluginId: 'parseRouterMap',
    apply(node: HvigorNode) {
      const hapCtx = (OhosPluginId.OHOS_HAP_PLUGIN) as OhosHapContext
      const moduleJson = ()
      const routerMapName = moduleJson['module']['routerMap'].split(':')[1]
      const dir = ()
      const srcFile = (dir, 'src', 'main', 'resources', 'base', 'profile', `${routerMapName}.json`)
      const json = FileUtil.readJson5(srcFile)
      const routerMapFile = (dir, 'src', 'main', 'ets', '')
      (routerMapFile)
      const routerMapArray = json['routerMap']
      let ss = ''
      for (const element of routerMapArray) {
        const name = element['name']
        ss += `  ${name} = '${name}',\n`
      }
      ss = `export enum Pages {\n${ss}}`
      (routerMapFile, ss)
    }
  }
}
export default {
  system: hapTasks,
  plugins:[parseRouterMap()]
}

We generate a file in the ets directory and generate corresponding enumeration values ​​for all navigation pages. When the page is redirected, we don’t have to worry about errors when using these enumeration values. The content is as follows

export enum Pages {
  dialog = 'dialog',
  web = 'web',
  login = 'login',
}

This is the article about the dynamic code generation of Hongmeng Development Hvigor plug-in. For more information about the dynamic code generation of Hongmeng Development Hvigor plug-in, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!