hvigorfile.ts 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. import { appTasks } from '@ohos/hvigor-ohos-plugin';
  2. import { HvigorPlugin, HvigorNode } from '@ohos/hvigor';
  3. import fs from 'fs';
  4. import path from 'path';
  5. function customPlugin(): HvigorPlugin {
  6. return {
  7. pluginId: 'customPlugin',
  8. apply(node: HvigorNode) {
  9. try {
  10. // console.log('node', JSON.stringify(node))
  11. // 根据node对象结构获取项目路径
  12. const projectPath = node.nodeDir.filePath;
  13. console.log('目标路径:', projectPath);
  14. // 获取所有子模块
  15. const modules = node.allSubNodes.filter(subNode => subNode.node.classKind === 'module');
  16. console.log('模块数量:', modules.length);
  17. // 打印每个模块的路径
  18. const modulePaths = [];
  19. modules.forEach((module, index) => {
  20. try {
  21. // 从module.node._nodePath获取模块路径
  22. const modulePath = module.node._nodePath;
  23. if (modulePath) {
  24. console.log(`模块 ${index + 1} 路径:`, modulePath);
  25. modulePaths.push(modulePath);
  26. } else {
  27. console.log(`模块 ${index + 1} 路径: 无法获取路径`);
  28. }
  29. } catch (error) {
  30. console.error(`获取模块 ${index + 1} 路径时出错:`, error);
  31. }
  32. });
  33. // 遍历并处理所有模块
  34. modulePaths.forEach((modulePath, index) => {
  35. console.log(`处理模块 ${index + 1}:`, modulePath);
  36. processModule(modulePath, projectPath);
  37. });
  38. } catch (error) {
  39. console.error('Error in custom plugin:', error);
  40. }
  41. }
  42. }
  43. function processModule(modulePath: string, projectPath: string) {
  44. try {
  45. // 构建pages目录路径 (基于模块路径)
  46. const pagesPath = path.join(modulePath, 'src', 'main', 'ets', 'pages');
  47. console.log('pages路径:', pagesPath);
  48. // 构建profile目录路径 (基于模块路径)
  49. const rawfilePath = path.join(modulePath, 'src', 'main', 'resources', 'base', 'profile');
  50. console.log('profile路径:', rawfilePath);
  51. // 确保profile目录存在
  52. if (!fs.existsSync(rawfilePath)) {
  53. fs.mkdirSync(rawfilePath, { recursive: true });
  54. }
  55. // router_map.json文件路径
  56. const routerMapPath = path.join(rawfilePath, 'router_map.json');
  57. // module.json5文件路径
  58. const moduleJsonPath = path.join(modulePath, 'src', 'main', 'module.json5');
  59. // 初始化routerMap
  60. let routerMap = {
  61. routerMap: []
  62. };
  63. // 如果router_map.json文件已存在,则读取现有内容
  64. if (fs.existsSync(routerMapPath)) {
  65. try {
  66. const existingContent = fs.readFileSync(routerMapPath, 'utf8');
  67. routerMap = JSON.parse(existingContent);
  68. console.log('读取现有的router_map.json文件');
  69. } catch (error) {
  70. console.error('读取router_map.json文件出错:', error);
  71. }
  72. }
  73. // 检查pages目录是否存在
  74. if (fs.existsSync(pagesPath)) {
  75. // 读取目录内容
  76. const files = fs.readdirSync(pagesPath);
  77. console.log(`Found ${files.length} files/directories in pages folder:`);
  78. // 遍历并处理每个文件
  79. files.forEach((file, index) => {
  80. const fullPath = path.join(pagesPath, file);
  81. const stat = fs.statSync(fullPath);
  82. const type = stat.isDirectory() ? '[DIR]' : '[FILE]';
  83. console.log(`${index + 1}. ${type} ${file}`);
  84. // 如果是文件,读取文件内容
  85. if (!stat.isDirectory() && file.endsWith('.ets')) {
  86. try {
  87. const content = fs.readFileSync(fullPath, 'utf8');
  88. // console.log(`Content of ${file}:`);
  89. // console.log(content);
  90. // 检查是否有@RouterPage修饰器
  91. if (content.includes('@RouterPage')) {
  92. // 生成Builder函数名(去掉Page后缀,加上Builder后缀)
  93. const fileNameWithoutExtension = file.replace('.ets', '');
  94. const builderName = fileNameWithoutExtension.replace(/Page$/, '') + 'Builder';
  95. // 检查是否已经存在Builder函数
  96. const builderRegex = new RegExp(`@Builder\\s+function\\s+${builderName}\\s*\\(\\)`, 'g');
  97. if (!builderRegex.test(content)) {
  98. // 构造新的内容,在文件末尾添加Builder函数
  99. const structName = fileNameWithoutExtension; // 假设struct名称与文件名相同
  100. const builderFunction = `\n@Builder\nfunction ${builderName}() {\n ${structName}()\n}\n`;
  101. const newContent = content + builderFunction;
  102. // 写入文件
  103. fs.writeFileSync(fullPath, newContent, 'utf8');
  104. console.log(`Added ${builderName} function to ${file}`);
  105. } else {
  106. console.log(`Builder function ${builderName} already exists in ${file}`);
  107. }
  108. // 添加到routerMap中
  109. const pageEntry = {
  110. name: fileNameWithoutExtension,
  111. pageSourceFile: `src/main/ets/pages/${file}`,
  112. buildFunction: builderName
  113. };
  114. // 检查是否已存在该条目
  115. const existingIndex = routerMap.routerMap.findIndex(item => item.name === fileNameWithoutExtension);
  116. if (existingIndex >= 0) {
  117. // 更新现有条目
  118. routerMap.routerMap[existingIndex] = pageEntry;
  119. } else {
  120. // 添加新条目
  121. routerMap.routerMap.push(pageEntry);
  122. }
  123. }
  124. console.log('----------------------------------------');
  125. } catch (readError) {
  126. console.error(`Error reading file ${file}:`, readError);
  127. }
  128. }
  129. });
  130. // 将routerMap写入router_map.json文件
  131. try {
  132. fs.writeFileSync(routerMapPath, JSON.stringify(routerMap, null, 2), 'utf8');
  133. console.log('router_map.json文件已更新');
  134. } catch (writeError) {
  135. console.error('写入router_map.json文件出错:', writeError);
  136. }
  137. // 更新module.json5文件,添加routerMap字段
  138. try {
  139. if (fs.existsSync(moduleJsonPath)) {
  140. const moduleJsonContent = fs.readFileSync(moduleJsonPath, 'utf8');
  141. // 使用正则表达式在"module": {后添加routerMap字段
  142. if (moduleJsonContent.includes('"module"')) {
  143. // 检查是否已经存在routerMap字段
  144. if (!moduleJsonContent.includes('"routerMap"')) {
  145. // 在"module": {后添加routerMap字段
  146. const updatedContent = moduleJsonContent.replace(
  147. /("module"\s*:\s*{)/,
  148. '$1\n "routerMap": "$profile:router_map",'
  149. );
  150. fs.writeFileSync(moduleJsonPath, updatedContent, 'utf8');
  151. console.log('module.json5文件已更新,添加了routerMap字段');
  152. } else {
  153. console.log('module.json5中已存在routerMap字段');
  154. }
  155. } else {
  156. console.log('module.json5中未找到"module"字段');
  157. }
  158. } else {
  159. console.log('module.json5文件不存在');
  160. }
  161. } catch (error) {
  162. console.error('更新module.json5文件出错:', error);
  163. }
  164. } else {
  165. console.log('Pages directory not found');
  166. }
  167. } catch (error) {
  168. console.error(`处理模块 ${modulePath} 时出错:`, error);
  169. }
  170. }
  171. }
  172. export default {
  173. system: appTasks, /* Built-in plugin of Hvigor. It cannot be modified. */
  174. plugins: [
  175. customPlugin() // 应用自定义Plugin
  176. ] /* Custom plugin to extend the functionality of Hvigor. */
  177. }