# generator **Repository Path**: harmony-free/generator ## Basic Information - **Project Name**: generator - **Description**: 这是鸿蒙hvigor的一个根据配置自动生成文件库 - **Primary Language**: Unknown - **License**: MIT - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 1 - **Forks**: 0 - **Created**: 2025-05-28 - **Last Updated**: 2025-07-22 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # refresh #### Description [中文](README.md) This is a file library automatically generated based on configuration by HONAM HVIGOR. #### Software Architecture Huawei Hvigor Script #### Installation [Click to download lib](./lib) 1、Manual import: Place the downloaded.tgz package into the project, and then in the `/hvigor/hvigor-config.json5` file, introduce `XXX` to replace the storage path. ``` /hvigor/hvigor-config.json5 { "dependencies": { "@free/generator": "file:../XXX.tgz" }, } ``` #### Instructions #### model Usage method 1、Introduce the hvigorfile.json5 file under the "entry" section. ``` /entry/hvigorfile.json5 import { jsonToModelPlugin } from '@free/generator'; // input: josn The entrance area, Default /entry/json/ // out: model The exit point, Default /entry/model/ export default { system: hapTasks, plugins:[ jsonToModelPlugin(input?:string,out?:string) ] } ``` 2、Execute the command `hvigorw --sync` #### router_map Usage method 1、Introduce the hvigorfile.json5 file under the "entry" section. ``` /entry/hvigorfile.json5 import { genNavRouterPlugin } from '@free/generator'; export default { system: hapTasks, plugins:[ genNavRouterPlugin() ] } ``` 2、Execute the command `hvigorw --sync` 3、Add @Router() to @Component ``` /// The configuration parameters can be left blank. The default component name will be used. /// name?:string|undefined Route name, Example 'home/page/name' /// isParams?:boolean Whether to carry parameters? Default: No parameters. false /// hideNavDes?:boolean Whether to hide the title bar of NavDestination? Default: hidden false @Router(config?:RouterConfig) @Component export struct HomePageName{ // ... } ``` 4、Jumping and callback, non-entry modules need to be written as '@module_name/HomePageName' ``` // push this.navPathStack.pushPathByName("home/page/name","hello", (res:PopInfo)=>{ console.log("this is a back parameter:" + JSON.stringify(res.result)); }) // pop this.navPathStack.pop("back parameter") ``` #### Usage of openCustomDialog 1、Introduce the hvigorfile.json5 file under the "entry" section. ``` /entry/hvigorfile.json5 import { genDialogPlugin } from '@free/generator'; export default { system: hapTasks, plugins:[ genDialogPlugin() ] } ``` 2、Execute the command `hvigorw --sync` 3、Add @Router() to @FreeDialog ``` @FreeDialog() // or @FreeDialog({name:"showApp"}) @Component export struct ShowAppComponent{ // ... } ``` 4、open Dialog ``` Dialog.show({name:"showApp",data:"hello dialog",onConfirm:(data)=>{ console.log("this is a back parameter:" + JSON.stringify(res.result)); }}) ``` 5、close Dialog ``` this.params?.close!(CallBackStatus.confirm,"data") ``` #### Plugin Details Hello everyone, welcome! Today, we will be discussing the scenario of automatically generating models using JSON in Harmony. Many students often make mistakes when writing model data, either by omitting or miswriting certain parameters, or by incorrectly specifying the data type of the parameters. This can lead to unexpected errors during development, which require multiple debugging attempts to identify the problem. In this session, I will guide you all through using the hvigor script to implement the generator to automatically generate models, ensuring the correctness of the models. 一、First, create a TypeScript project and import the necessary dependencies. You can refer to [hvigor plugin development](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/ide-hvigor-plugin) for details. Additionally, take a look at hvigor - it is a lightweight build tool provided by Huawei, which enables the automatic generation of models by writing JavaScript code. ![](https://alliance-communityfile-drcn.dbankcdn.com/FileServer/getFile/cmtybbs/137/390/427/0080086000137390427.20250617104959.45816006082122898408488261424687:50001231000000:2800:91A434C399284E0ACF4F9CFA47414DF9626D7F217A2C1BA3C37581859C4E0706.png) 二、The data in the JSON file is read from the specified path of the JSON data file using the hvigor and fs-extra plugins. 1、Traverse and read the JSON file ``` traverseDirectory(path:string,complete: (dirent: fs.Dirent) => void){ fs.readdir(path, { withFileTypes: true },(err,dirents)=>{ if (err) { log(`Error reading directory ${path}:${err}`); return; } dirents.forEach((dirent)=>{ const fullPath = `${path}/${dirent.name}`; if (dirent.isDirectory()){ // If it is a folder, make a recursive call fs.mkdir(`${this.config.out}/${dirent.name}`) this.traverseDirectory(fullPath,complete); }else{ complete(dirent) } }) }) } ``` 2、Read the file data ``` this.traverseDirectory(this.config.input,(dirent)=>{ let buf = fs.readFileSync(dirent.parentPath + "/" + dirent.name,{encoding:'utf-8'}) }) ``` 三、Create the model file using the fs-extra plugin and output it to the "out" folder. Create the model file based on the JSON file. Convert the JSON data into model data using jsonToModel, and then write it into the model file. 1、Convert JSON data to model data ``` jsonToModel(json:object,name:string):string{ let data = Object.entries(json); let body = ""; let init = `\tconstructor(face:${name}Face) {\n\t\tif(face==null)`; let otherMap:Map = new Map() data.forEach((k)=>{ if(k[1] instanceof Array){ body += `\t${k[0]}:Array<${this.arrayToModel(k[0],k[1],otherMap,name)}> | undefined \n` }else if(k[1] != null && typeof k[1] == "object"){ let objName = name + k[0].substring(0, 1).toUpperCase() + k[0].substring(1); otherMap.set(objName,k[1]) body += `\t${k[0]}:${objName}Model | undefined \n` }else{ body += `\t${k[0]}:${typeof k[1]} | undefined \n` } init += `\t\tthis.${k[0]} = face.${k[0]} \n` }) let model = `export interface ${name}Face{ \n ${body}}\n\n` model += `export class ${name}Model implements ${name}Face{\n${body}\n}\n\n` otherMap.forEach((v,k)=>{ model += this.jsonToModel(v,k) }) return model } // Handling array nesting issues arrayToModel(k:string,v:Array,otherMap:Map,name:string):string{ if(v.length > 0){ if(typeof v[0] == "object"){ if(v[0] instanceof Array){ return `Array<${this.arrayToModel(k,v[0],otherMap,name)}>`; }else{ let objName = name + k.substring(0, 1).toUpperCase() + k.substring(1); otherMap.set(objName,v[0]) return objName + "Model" } }else{ return typeof v[0] } }else{ return "object" } } ``` 2、Based on creating the model file and writing the model data into the model file ``` this.traverseDirectory(this.config.input,(dirent)=>{ let buf = fs.readFileSync(dirent.parentPath + "/" + dirent.name,{encoding:'utf-8'}) let fileName = dirent.name.split('.')[0]; fileName = fileName.substring(0, 1).toUpperCase() + fileName.substring(1); const filePath = `${this.config.out}/${fileName}.g.ets`; let model = this.jsonToModel(JSON.parse(buf),fileName) fs.writeFileSync(filePath,model) }) ``` Note: The complete code has been submitted to [Code Repository](https://gitee.com/harmony-free/generator),Go to [Download.tgz package](https://gitee.com/harmony-free/generator/tree/master/lib) 1、Manual Import: Place the downloaded.tgz package into the project. In the `/hvigor/hvigor-config.json5` file, introduce `XXX` to replace the storage path. ``` /hvigor/hvigor-config.json5 { "dependencies": { "@free/generator": "file:../XXX.tgz" }, } ``` 2. Introduce the hvigorfile.json5 file under the "entry" directory. ``` /entry/hvigorfile.json5 import { jsonToModelPlugin } from '@free/generator'; // Input: The location for JSON input. Default: /entry/json/ // Output: The location for the model. Default: /entry/model/ export default { system: hapTasks, plugins:[ jsonToModelPlugin(input?:string,out?:string) ] } ``` 3、Execute the command `hvigorw --sync` ![](https://alliance-communityfile-drcn.dbankcdn.com/FileServer/getFile/cmtybbs/137/390/427/0080086000137390427.20250617112745.16036371874079713910992205651937:50001231000000:2800:AC9344AF3B1CAC38757737C4743BA012148629FA3BF1ECEF3D35C129883A6F80.png) If you like this content, please give a little heart! #### Contribution 1. Fork the repository 2. Create Feat_xxx branch 3. Commit your code 4. Create Pull Request #### Gitee Feature 1. You can use Readme\_XXX.md to support different languages, such as Readme\_en.md, Readme\_zh.md 2. Gitee blog [blog.gitee.com](https://blog.gitee.com) 3. Explore open source project [https://gitee.com/explore](https://gitee.com/explore) 4. The most valuable open source project [GVP](https://gitee.com/gvp) 5. The manual of Gitee [https://gitee.com/help](https://gitee.com/help) 6. The most popular members [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/)