const $Fs = require('fs'); // 引入文件模块 const md5 = require('md5'); const filePath = './src/pages/' const filePath2 = './src/common/' let preveMd5 = null //跟踪文件 $Fs.watch(filePath,(event,filename)=>{ if (!$Fs.existsSync(filePath + filename)) { return } var currentMd5 = md5($Fs.readFileSync(filePath + filename)) if (currentMd5 == preveMd5) { return } preveMd5 = currentMd5 console.log(`${filePath}文件发生更新`) let files = $Fs.readdirSync('./src/pages'); // 读取pages页面文件目录下的html文件 files.forEach((file,index) => { // 遍历获得的所有页面文件 let old_data = $Fs.readFileSync('./src/pages/' + file,'utf8'); // 读取当前文件的内容 let new_data = old_data.replace(/\.*\<\/include\>/gi,(match,p1,offset,string) => {//查找html文件中include标签 let inc_data = $Fs.readFileSync('./src/common/' + p1,'utf8'); // p1是第一个括号匹配到的值,也就是include包含的文件路径,读取此公共文件 return inc_data; // 此回调函数返回的值,将替换正则匹配到的字符串 }); $Fs.writeFileSync('./dist/' + file,new_data); //将include标签被替换后新的html内容,写入到dist资源目录的同名file文件中(不存在会自动新建)。 }); console.log('重新生成成功1'); }) $Fs.watch(filePath2,(event,filename)=>{ var currentMd5 = md5($Fs.readFileSync(filePath2 + filename)) if (currentMd5 == preveMd5) { return } preveMd5 = currentMd5 console.log(`${filePath2}文件发生更新`) let files = $Fs.readdirSync('./src/pages'); // 读取pages页面文件目录下的html文件 files.forEach((file,index) => { // 遍历获得的所有页面文件 let old_data = $Fs.readFileSync('./src/pages/' + file,'utf8'); // 读取当前文件的内容 let new_data = old_data.replace(/\.*\<\/include\>/gi,(match,p1,offset,string) => {//查找html文件中include标签 let inc_data = $Fs.readFileSync('./src/common/' + p1,'utf8'); // p1是第一个括号匹配到的值,也就是include包含的文件路径,读取此公共文件 return inc_data; // 此回调函数返回的值,将替换正则匹配到的字符串 }); $Fs.writeFileSync('./dist/' + file,new_data); //将include标签被替换后新的html内容,写入到dist资源目录的同名file文件中(不存在会自动新建)。 }); console.log('重新生成成功2'); }) //生成文件 let files = $Fs.readdirSync('./src/pages'); // 读取pages页面文件目录下的html文件 files.forEach((file,index) => { // 遍历获得的所有页面文件 let old_data = $Fs.readFileSync('./src/pages/' + file,'utf8'); // 读取当前文件的内容 let new_data = old_data.replace(/\.*\<\/include\>/gi,(match,p1,offset,string) => {//查找html文件中include标签 let inc_data = $Fs.readFileSync('./src/common/' + p1,'utf8'); // p1是第一个括号匹配到的值,也就是include包含的文件路径,读取此公共文件 return inc_data; // 此回调函数返回的值,将替换正则匹配到的字符串 }); $Fs.writeFileSync('./dist/' + file,new_data); //将include标签被替换后新的html内容,写入到dist资源目录的同名file文件中(不存在会自动新建)。 }); console.log('生成成功');