瀏覽代碼

新增router插件

chenritian 1 月之前
父節點
當前提交
f3dd16f70c

+ 1 - 1
commons/basic/Index.ets

@@ -1,5 +1,5 @@
 export { registerFontUtil } from './src/main/ets/utils/RegisterFontUtil'
-
+export { RouterPage } from './src/main/ets/ts'
 export { YTToast } from './src/main/ets/utils/YTToast'
 
 export { ContextHelper } from './src/main/ets/utils/ContextHelper'

+ 7 - 0
commons/basic/src/main/ets/ts/index.ts

@@ -0,0 +1,7 @@
+
+
+
+// 类装饰器
+export function RouterPage(target: any) {
+  console.log("decorateKlass")
+}

+ 3 - 0
commons/basic/src/main/resources/base/profile/router_map.json

@@ -0,0 +1,3 @@
+{
+  "routerMap": []
+}

+ 13 - 0
features/feature/src/main/ets/pages/ChaoYiPage.ets

@@ -0,0 +1,13 @@
+import { RouterPage } from 'basic';
+
+@Component
+@RouterPage
+struct ChaoYiPage {
+  build() {
+
+  }
+}
+@Builder
+function ChaoYiBuilder() {
+  ChaoYiPage()
+}

+ 13 - 0
features/feature/src/main/ets/pages/HelloPage.ets

@@ -0,0 +1,13 @@
+import { RouterPage } from 'basic';
+
+@Component
+@RouterPage
+struct HelloPage {
+  build() {
+
+  }
+}
+@Builder
+function HelloBuilder() {
+  HelloPage()
+}

+ 0 - 1
features/feature/src/main/module.json5

@@ -3,7 +3,6 @@
     "name": "feature",
     "type": "shared",
     "description": "$string:shared_desc",
-    "routerMap": "$profile:router_map",
     "deviceTypes": [
       "phone"
     ],

+ 10 - 1
features/feature/src/main/resources/base/profile/router_map.json

@@ -1,5 +1,14 @@
 {
   "routerMap": [
-
+    {
+      "name": "ChaoYiPage",
+      "pageSourceFile": "src/main/ets/pages/ChaoYiPage.ets",
+      "buildFunction": "ChaoYiBuilder"
+    },
+    {
+      "name": "HelloPage",
+      "pageSourceFile": "src/main/ets/pages/HelloPage.ets",
+      "buildFunction": "HelloBuilder"
+    }
   ]
 }

+ 206 - 1
hvigorfile.ts

@@ -1,6 +1,211 @@
 import { appTasks } from '@ohos/hvigor-ohos-plugin';
+import { HvigorPlugin, HvigorNode } from '@ohos/hvigor';
+import fs from 'fs';
+import path from 'path';
+
+function customPlugin(): HvigorPlugin {
+    return {
+
+        pluginId: 'customPlugin',
+        apply(node: HvigorNode) {
+            try {
+
+                console.log('node', JSON.stringify(node))
+                // 根据node对象结构获取项目路径
+                const projectPath = node.nodeDir.filePath;
+                console.log('目标路径:', projectPath);
+
+
+                // 获取所有子模块
+                const modules = node.allSubNodes.filter(subNode => subNode.node.classKind === 'module');
+                console.log('模块数量:', modules.length);
+
+                // 打印每个模块的路径
+                const modulePaths = [];
+                modules.forEach((module, index) => {
+                    try {
+                        // 从module.node._nodePath获取模块路径
+                        const modulePath = module.node._nodePath;
+                        if (modulePath) {
+                            console.log(`模块 ${index + 1} 路径:`, modulePath);
+                            modulePaths.push(modulePath);
+                        } else {
+                            console.log(`模块 ${index + 1} 路径: 无法获取路径`);
+                        }
+                    } catch (error) {
+                        console.error(`获取模块 ${index + 1} 路径时出错:`, error);
+                    }
+                });
+
+                // 遍历并处理所有模块
+                modulePaths.forEach((modulePath, index) => {
+                    console.log(`处理模块 ${index + 1}:`, modulePath);
+                    processModule(modulePath, projectPath);
+                });
+
+            } catch (error) {
+                console.error('Error in custom plugin:', error);
+            }
+        }
+    }
+
+    function processModule(modulePath: string, projectPath: string) {
+        try {
+            // 构建pages目录路径 (基于模块路径)
+            const pagesPath = path.join(modulePath, 'src', 'main', 'ets', 'pages');
+            console.log('pages路径:', pagesPath);
+
+            // 构建profile目录路径 (基于模块路径)
+            const rawfilePath = path.join(modulePath, 'src', 'main', 'resources', 'base', 'profile');
+            console.log('profile路径:', rawfilePath);
+
+            // 确保profile目录存在
+            if (!fs.existsSync(rawfilePath)) {
+                fs.mkdirSync(rawfilePath, { recursive: true });
+            }
+
+            // router_map.json文件路径
+            const routerMapPath = path.join(rawfilePath, 'router_map.json');
+
+            // module.json5文件路径
+            const moduleJsonPath = path.join(modulePath, 'src', 'main', 'module.json5');
+
+            // 初始化routerMap
+            let routerMap = {
+                routerMap: []
+            };
+
+            // 如果router_map.json文件已存在,则读取现有内容
+            if (fs.existsSync(routerMapPath)) {
+                try {
+                    const existingContent = fs.readFileSync(routerMapPath, 'utf8');
+                    routerMap = JSON.parse(existingContent);
+                    console.log('读取现有的router_map.json文件');
+                } catch (error) {
+                    console.error('读取router_map.json文件出错:', error);
+                }
+            }
+
+            // 检查pages目录是否存在
+            if (fs.existsSync(pagesPath)) {
+                // 读取目录内容
+                const files = fs.readdirSync(pagesPath);
+                console.log(`Found ${files.length} files/directories in pages folder:`);
+
+                // 遍历并处理每个文件
+                files.forEach((file, index) => {
+                    const fullPath = path.join(pagesPath, file);
+                    const stat = fs.statSync(fullPath);
+                    const type = stat.isDirectory() ? '[DIR]' : '[FILE]';
+                    console.log(`${index + 1}. ${type} ${file}`);
+
+                    // 如果是文件,读取文件内容
+                    if (!stat.isDirectory() && file.endsWith('.ets')) {
+                        try {
+                            const content = fs.readFileSync(fullPath, 'utf8');
+                            console.log(`Content of ${file}:`);
+                            console.log(content);
+
+                            // 检查是否有@RouterPage修饰器
+                            if (content.includes('@RouterPage')) {
+                                // 生成Builder函数名(去掉Page后缀,加上Builder后缀)
+                                const fileNameWithoutExtension = file.replace('.ets', '');
+                                const builderName = fileNameWithoutExtension.replace(/Page$/, '') + 'Builder';
+
+                                // 检查是否已经存在Builder函数
+                                if (!content.includes(`@Builder\nfunction ${builderName}()`)) {
+                                    // 构造新的内容,在文件末尾添加Builder函数
+                                    const structName = fileNameWithoutExtension; // 假设struct名称与文件名相同
+                                    const builderFunction = `\n@Builder\nfunction ${builderName}() {\n  ${structName}()\n}\n`;
+                                    const newContent = content + builderFunction;
+
+                                    // 写入文件
+                                    fs.writeFileSync(fullPath, newContent, 'utf8');
+                                    console.log(`Added ${builderName} function to ${file}`);
+                                } else {
+                                    console.log(`Builder function ${builderName} already exists in ${file}`);
+                                }
+
+                                // 添加到routerMap中
+                                const pageEntry = {
+                                    name: fileNameWithoutExtension,
+                                    pageSourceFile: `src/main/ets/pages/${file}`,
+                                    buildFunction: builderName
+                                };
+
+                                // 检查是否已存在该条目
+                                const existingIndex = routerMap.routerMap.findIndex(item => item.name === fileNameWithoutExtension);
+                                if (existingIndex >= 0) {
+                                    // 更新现有条目
+                                    routerMap.routerMap[existingIndex] = pageEntry;
+                                } else {
+                                    // 添加新条目
+                                    routerMap.routerMap.push(pageEntry);
+                                }
+                            }
+
+                            console.log('----------------------------------------');
+                        } catch (readError) {
+                            console.error(`Error reading file ${file}:`, readError);
+                        }
+                    }
+                });
+
+                // 将routerMap写入router_map.json文件
+                try {
+                    fs.writeFileSync(routerMapPath, JSON.stringify(routerMap, null, 2), 'utf8');
+                    console.log('router_map.json文件已更新');
+                } catch (writeError) {
+                    console.error('写入router_map.json文件出错:', writeError);
+                }
+
+                // 更新module.json5文件,添加routerMap字段
+                try {
+                    if (fs.existsSync(moduleJsonPath)) {
+                        const moduleJsonContent = fs.readFileSync(moduleJsonPath, 'utf8');
+
+                        // 使用正则表达式在"type": "entry"后添加routerMap字段
+                        if (moduleJsonContent.includes('"type": "entry"')) {
+                            // 检查是否已经存在routerMap字段
+                            if (!moduleJsonContent.includes('"routerMap"')) {
+                                // 在"type": "entry"后添加routerMap字段
+                                const updatedContent = moduleJsonContent.replace(
+                                    /("type":\s*"entry"[,\s\n\r]*)/,
+                                    '$1"routerMap": "$profile:router_map",\n    '
+                                );
+
+                                fs.writeFileSync(moduleJsonPath, updatedContent, 'utf8');
+                                console.log('module.json5文件已更新,添加了routerMap字段');
+                            } else {
+                                console.log('module.json5中已存在routerMap字段');
+                            }
+                        } else {
+                            console.log('module.json5中未找到"type": "entry"');
+                        }
+                    } else {
+                        console.log('module.json5文件不存在');
+                    }
+                } catch (error) {
+                    console.error('更新module.json5文件出错:', error);
+                }
+            } else {
+                console.log('Pages directory not found');
+            }
+        } catch (error) {
+            console.error(`处理模块 ${modulePath} 时出错:`, error);
+        }
+    }
+}
+
+
+
+
+
+
 
 export default {
     system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
-    plugins:[]         /* Custom plugin to extend the functionality of Hvigor. */
+    plugins: [
+        customPlugin()  // 应用自定义Plugin
+    ]         /* Custom plugin to extend the functionality of Hvigor. */
 }

+ 1 - 0
products/entry/src/main/module.json5

@@ -2,6 +2,7 @@
   "module": {
     "name": "entry",
     "type": "entry",
+    "routerMap": "$profile:router_map",
     "description": "$string:module_desc",
     "mainElement": "EntryAbility",
     "deviceTypes": [

+ 3 - 0
products/entry/src/main/resources/base/profile/router_map.json

@@ -0,0 +1,3 @@
+{
+  "routerMap": []
+}