如何在含百余个组件的ReactJS项目中识别重复图片?
识别React项目中组件间重复图片的简便方法
下面是几个实用方案,能快速定位分散在各组件images文件夹中的重复图片:
1. 基于文件哈希值的脚本/命令行方案
重复图片的文件内容完全一致,对应的哈希值(如MD5、SHA-1)也会相同,这是最准确的判断方式:
- 命令行快速验证:
- Linux/macOS:执行
find ./src -path "*/images/*" -type f \( -iname "*.png" -o -iname "*.svg" -o -iname "*.jpg" \) -exec md5sum {} \; | sort | uniq -d -w 32,直接输出所有哈希重复的文件。 - Windows:在PowerShell中运行
Get-ChildItem -Path ./src -Recurse -Include *.png,*.svg,*.jpg | ForEach-Object { Get-FileHash -Path $_.FullName -Algorithm MD5 } | Group-Object -Property Hash | Where-Object { $_.Count -gt 1 }。
- Linux/macOS:执行
- 自定义Node.js脚本:
写一个简单脚本遍历所有images文件夹,计算文件哈希并归类重复项,示例代码如下:
把脚本存为const fs = require('fs').promises; const path = require('path'); const crypto = require('crypto'); async function findDuplicateImages(rootDir) { const hashMap = new Map(); async function traverse(dir) { const entries = await fs.readdir(dir, { withFileTypes: true }); for (const entry of entries) { const fullPath = path.join(dir, entry.name); if (entry.isDirectory()) { if (entry.name === 'images') { const imageFiles = await fs.readdir(fullPath, { withFileTypes: true }); for (const img of imageFiles) { if (img.isFile() && /\.(png|svg|jpg|jpeg|gif)$/i.test(img.name)) { const imgPath = path.join(fullPath, img.name); const buffer = await fs.readFile(imgPath); const hash = crypto.createHash('md5').update(buffer).digest('hex'); hashMap.has(hash) ? hashMap.get(hash).push(imgPath) : hashMap.set(hash, [imgPath]); } } } else { await traverse(fullPath); } } } } await traverse(rootDir); const duplicates = Array.from(hashMap.entries()).filter(([_, paths]) => paths.length > 1); duplicates.forEach(([hash, paths]) => { console.log(`哈希值 ${hash} 的重复文件:`); paths.forEach(p => console.log(`- ${p}`)); console.log('---'); }); } findDuplicateImages('./src');find-duplicates.js,运行node find-duplicates.js即可得到结果。
2. 可视化重复文件查找工具
用现成桌面工具扫描项目目录,操作直观还能预览图片对比:
- Windows:Duplicate Cleaner
- macOS:Gemini 2
- 跨平台:FSlint
只需指定项目根目录,过滤images文件夹或图片格式,就能快速找出重复项。
3. SVG图标特殊处理
如果项目中有大量SVG图标,部分可能因多余注释、空格或无关属性(如随机id)导致哈希不同,但实际是同一图标:
- 先用SVGO(SVG优化工具)批量优化所有SVG文件,统一移除冗余内容;
- 再用上述哈希方法或工具对比,即可识别这类“伪重复”的SVG图标。
内容的提问来源于stack exchange,提问作者Sbagaria2710
相关产品推荐
相关产品推荐

