问题具体是属于node.js领域,可以参考如下demo:import { hapTasks } from '@ohos/hvigor-ohos-plugin'; import * as fs from 'fs'; import * as path from 'path'; import { exec } from 'child_process'; export function customPluginFunction1(str?: string) { return { pluginId: 'CustomPluginID1', apply(pluginContext) { pluginContext.registerTask({ // 编写自定义任务 name: 'customTask1', run: (taskContext) => { // 插件主体 // 执行git命令获取提交id exec('git rev-parse --short HEAD', (error, stdout, stderr) => { if (error) { console.error(`执行命令出错: ${error.message}`); return; } console.log(`命令输出: ${stdout}`); const filePath = path.join(__dirname, 'src/main/ets/pages/GitTestClass.ets'); console.log('filePath = ', filePath) const newValue = '123456' // 读取ets文件内容 fs.readFile(filePath, 'utf8', (err, data) => { console.log('fs.readFile') if (err) { console.log('读取文件时发生错误') console.error('读取文件时发生错误:', err); return; } // 使用正则表达式替换内容 // const pattern = /@State test: string = '[^']*';/g // if (pattern.test(data)) { // console.log("匹配成功!"); // } else { // console.log("匹配失败!"); // } // 将git命令返回的id写入ets代码 const updatedContent = data.replace(/@State test: string = '[^']*';/g, `@State test: string = '${newValue}';`); console.log('updatedContent = ', updatedContent) // 写入文件 fs.writeFile(filePath, updatedContent, 'utf8', (err) => { if (err) { console.error('写入文件时发生错误:', err); return; } console.log('文件已更新'); }); }); }); }, // 确认自定义任务插入位置 dependencies: ['default@BuildJS'], postDependencies: ['default@CompileArkTS'] }) } } } export default { system: hapTasks, /* Built-in plugin of Hvigor. It cannot be modified. */ plugins:[ customPluginFunction1() ]/* Custom plugin to extend the functionality of Hvigor. */ }
问题具体是属于node.js领域,可以参考如下demo: