replace-placeholder-links.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. const fs = require('fs');
  2. const path = require('path');
  3. // 定义要替换的目录
  4. const srcDir = path.join(__dirname, 'src');
  5. // 定义要搜索的文件扩展名
  6. const fileExtensions = ['.ts', '.html'];
  7. // 替换 via.placeholder.com 链接的函数
  8. function replacePlaceholderLinks(fileContent, filePath) {
  9. let modifiedContent = fileContent;
  10. let replacementCount = 0;
  11. // 正则表达式匹配 via.placeholder.com 链接
  12. const placeholderRegex = /https:\/\/via\.placeholder\.com\/(\d+)x(\d+)\/([0-9A-Fa-f]+)\/([0-9A-Fa-f]+)\?text=([^"']*)/g;
  13. // 替换匹配的链接
  14. modifiedContent = modifiedContent.replace(placeholderRegex, (match, width, height, bgColor, textColor, text) => {
  15. replacementCount++;
  16. // 根据文件类型和上下文决定返回什么
  17. if (filePath.endsWith('.html')) {
  18. // 对于HTML文件,返回一个带有内联样式的div作为占位图
  19. return `<div style="width: ${width}px; height: ${height}px; background-color: #${bgColor}; color: #${textColor}; display: flex; align-items: center; justify-content: center; font-size: ${Math.min(width, height) / 3}px; font-weight: bold;">${text}</div>`;
  20. } else if (filePath.endsWith('.ts')) {
  21. // 对于TypeScript文件,返回一个本地占位图配置对象
  22. return `{ width: ${width}, height: ${height}, bgColor: '#${bgColor}', textColor: '#${textColor}', text: '${text}' }`;
  23. }
  24. // 如果不是HTML或TS文件,保持原样
  25. return match;
  26. });
  27. return { modifiedContent, replacementCount };
  28. }
  29. // 遍历目录中的文件
  30. function traverseDirectory(dir) {
  31. const files = fs.readdirSync(dir);
  32. let totalReplacements = 0;
  33. files.forEach(file => {
  34. const filePath = path.join(dir, file);
  35. const stat = fs.statSync(filePath);
  36. if (stat.isDirectory()) {
  37. const subDirReplacements = traverseDirectory(filePath);
  38. totalReplacements += subDirReplacements;
  39. } else if (fileExtensions.some(ext => file.endsWith(ext))) {
  40. // 读取文件内容
  41. const fileContent = fs.readFileSync(filePath, 'utf8');
  42. // 替换 via.placeholder.com 链接
  43. const { modifiedContent, replacementCount } = replacePlaceholderLinks(fileContent, filePath);
  44. // 如果有替换,写入文件
  45. if (replacementCount > 0) {
  46. fs.writeFileSync(filePath, modifiedContent, 'utf8');
  47. console.log(`已替换 ${filePath} 中的 ${replacementCount} 个placeholder链接`);
  48. totalReplacements += replacementCount;
  49. }
  50. }
  51. });
  52. return totalReplacements;
  53. }
  54. // 执行替换操作
  55. console.log('开始替换 via.placeholder.com 链接...');
  56. const totalReplacements = traverseDirectory(srcDir);
  57. console.log(`替换完成!总共替换了 ${totalReplacements} 个placeholder链接。`);