如何用JavaScript获取目录文件路径,开发未导入图片检测npm包?
实现未导入图片检测npm包的技术方案
一、动态提取目录文件路径(图片目录)
用Node.js内置的fs.promises结合递归遍历处理目录(含子目录),收集指定格式的图片路径:
const fs = require('fs').promises; const path = require('path'); // 递归遍历目录,收集所有图片文件的相对路径 async function collectImagePaths(imageDir) { const imagePaths = []; const items = await fs.readdir(imageDir, { withFileTypes: true }); for (const item of items) { const fullPath = path.join(imageDir, item.name); if (item.isDirectory()) { // 递归处理子目录 const subDirPaths = await collectImagePaths(fullPath); imagePaths.push(...subDirPaths); } else { // 过滤目标图片格式,可按需扩展 const ext = path.extname(item.name).toLowerCase(); if (['.png', '.jpg', '.jpeg', '.gif', '.svg'].includes(ext)) { // 转换为相对于项目根目录的路径,适配代码中的引用格式 const relativePath = path.relative(process.cwd(), fullPath).replace(/\\/g, '/'); imagePaths.push(relativePath); } } } return imagePaths; }
二、遍历目标目录,检查文件是否包含图片路径
同样递归遍历业务代码目录,读取指定类型文件的内容,匹配已收集的图片路径:
// 检查单个文件是否包含目标路径 async function checkFileForPaths(filePath, targetPaths) { try { const content = await fs.readFile(filePath, 'utf8'); return targetPaths.filter(path => content.includes(path)); } catch (err) { console.error(`读取文件失败: ${filePath}`, err); return []; } } // 递归扫描目标目录,筛选未被引用的图片 async function scanTargetDir(targetDir, imagePaths) { let unusedImages = [...imagePaths]; const items = await fs.readdir(targetDir, { withFileTypes: true }); for (const item of items) { const fullPath = path.join(targetDir, item.name); // 跳过node_modules等无需检查的目录 if (item.isDirectory() && item.name === 'node_modules') continue; if (item.isDirectory()) { // 递归处理子目录,更新未使用图片列表 const subDirUnused = await scanTargetDir(fullPath, unusedImages); unusedImages = subDirUnused; } else { // 过滤需要检查的代码文件类型 const ext = path.extname(item.name).toLowerCase(); if (['.js', '.jsx', '.ts', '.tsx', '.vue', '.svelte'].includes(ext)) { const usedPaths = await checkFileForPaths(fullPath, unusedImages); // 从列表中移除已被引用的图片路径 usedPaths.forEach(path => { const index = unusedImages.indexOf(path); if (index !== -1) unusedImages.splice(index, 1); }); } } } return unusedImages; }
三、整合调用示例
// 主函数:入口调用 async function findUnusedImages(imageDir, targetDir) { const imagePaths = await collectImagePaths(imageDir); const unusedImages = await scanTargetDir(targetDir, imagePaths); console.log('未被导入的图片:', unusedImages); return unusedImages; } // 示例调用:图片目录为./assets/images,代码目录为./src findUnusedImages('./assets/images', './src');
关键注意事项
- 路径格式统一:将Windows路径的反斜杠替换为正斜杠,确保和代码中的引用格式一致,避免匹配失败。
- 别名适配:如果项目用了路径别名(如
@/assets/xxx.png),需将收集的图片路径转换为别名格式后再匹配。 - 性能优化:大目录场景下,可通过
Promise.all并行处理文件读取,同时控制并发数避免资源占用过高。
内容的提问来源于stack exchange,提问作者Joseph Walsh
相关产品推荐
相关产品推荐

