1 Star 0 Fork 8

chaimu/function-realization

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
beforeCompileScript.js 4.91 KB
一键复制 编辑 原始数据 按行查看 历史
林志腾 提交于 2024-02-26 18:46 . feat: 改变文件位置和样式优化
let path = require('path');
const fs = require('fs');
/**
* @description 读取文件夹下面的文件夹名称
* @param path 文件夹路径 string
* @returns 返回一个promise对象,resolve返回文件夹名称数组
*/
const readdir = (path) => {
return new Promise((resolve, reject) => {
fs.readdir(path, { withFileTypes: true }, (err, files) => {
if (err) {
reject(err);
}
const folderNames = files.filter(file => file.isDirectory()).map(folder => folder.name);
return resolve(folderNames);
})
})
}
/**
* @description 同步读取文件内容
* @param path 文件路径 string
* @returns 返回文件内容 string
*/
const readFile = (path) => {
return fs.readFileSync(path, (err, data) => {
if (err) {
return '';
}
return data;
})
}
/** 路由文件地址*/
let routerPath = path.join(__dirname, 'src', 'router', 'index.js');
// 读取文件内容
fs.readFile(routerPath, 'utf-8', (err, data) => {
if (err) {
console.error('读取文件时出错:', err);
return;
}
let startInd = data.indexOf('childrenList');
//从开始下标开始寻找
let resultStartInd = data.indexOf('[', startInd);
let resultEndInd = data.indexOf(']', startInd);
/** 需要替换的str*/
let replaceStr = data.substring(resultStartInd, resultEndInd + 1);
/** 原本文件中的路由列表*/
let originalList = replaceStr
originalList = originalList.replace(/\</g, '"<')
originalList = originalList.replace(/\/\>/g, '/>"')
originalList = JSON.parse(originalList);
/** 是否需要更新路由*/
let isChange = false;
/** 替换的路由列表*/
let replacingContent = [];
readdir(path.join(__dirname, 'src', 'pages','exampleList')).then(res => {
let content = {}
res.forEach((name) => {
content = {};
try {
let filePath = path.join(__dirname, 'src', 'pages','exampleList', name, 'pageConfig.ts')
let fileData = readFile(filePath).toString();
let startInd = fileData.indexOf('{')
let endInd = fileData.lastIndexOf('}');
let resultData = fileData.substring(startInd, endInd + 1);
//正则去除空白符
resultData = resultData.replace(/\s/g, '')
//正则 ' 变为 "
resultData = resultData.replace(/\'/g, '"')
//正则去掉}前面的,
resultData = resultData.replace(/\,(?=\})/g, '')
//为key加上双引号
resultData = resultData.replace(/([a-zA-Z0-9]+?):/g, '"$1":');
resultData = JSON.parse((resultData))
content = {
...resultData,
path: `${name}`,
sortInd: `${resultData.sortInd ? resultData.sortInd : res.length}`,
element: `<${name.charAt(0).toUpperCase() + name.slice(1)} />`,
}
replacingContent.push(content);
} catch (error) {
content = {
path: `${name}`,
sortInd: `${res.length}`,
element: `<${name.charAt(0).toUpperCase() + name.slice(1)} />`,
}
replacingContent.push(content);
}
})
return res
}).then((res) => {
// 按照sortInd,从小到大排序
replacingContent = replacingContent.sort((a, b) => {
return a.sortInd - b.sortInd
})
if (replacingContent.length !== originalList.length) {
isChange = true;
}
if (!isChange) {
for (let i = 0; i < replacingContent.length; i++) {
let keys = Object.keys(replacingContent[i]);
/** 需要检查的key列表*/
let checkKeys = keys.filter((item) => {
return !['element', 'path'].includes(item)
})
/** 检查长度是否一样*/
if (keys.length != Object.keys(originalList[i]).length) {
isChange = true;
break;
}
/** 检查key对相应的value是否一致*/
for (let j = 0; j < keys.length; j++) {
if (checkKeys.includes(keys[j]) && replacingContent[i][keys[j]] != originalList[i][keys[j]]) {
isChange = true;
break;
}
}
}
}
if (isChange) {
// 替换文件内容
let updatedContent = data.replace(replaceStr, JSON.stringify(
replacingContent
));
//去除导入的组件,同时去掉回车符
updatedContent = updatedContent.replace(/import.*from.*@.*\S/g, ' ')
updatedContent = updatedContent.trim();
// import 导入组件
res.forEach((name) => {
updatedContent = `import ${name.charAt(0).toUpperCase() + name.slice(1)} from '@/pages/exampleList/${name}/index.tsx'\n`.concat(updatedContent)
})
updatedContent = updatedContent.replace(/\"\</g, '<')
updatedContent = updatedContent.replace(/\>\"/g, '>')
// 将更新后的内容写入文件
fs.writeFile(routerPath, updatedContent, 'utf-8', (err) => {
if (err) {
console.error('写入文件时出错:', err);
return;
}
console.log('文件内容已成功替换!');
});
}
})
});
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/gtl521/function-realization.git
git@gitee.com:gtl521/function-realization.git
gtl521
function-realization
function-realization
master

搜索帮助