求自动将项目文件夹图片存入public array的脚本
自动批量生成图片数组的解决方案
场景1:Node.js预生成数组文件
适合需要提前生成固定数组文件的场景,运行一次脚本即可完成所有图片路径的收集:
const fs = require('fs'); const path = require('path'); // 配置项:根据你的项目结构修改路径 const imgFolderPath = path.join(__dirname, 'public/images'); // 图片所在文件夹 const outputFilePath = path.join(__dirname, 'src/imageArray.js'); // 生成的数组文件位置 const allowedImageExts = ['.jpg', '.jpeg', '.png', '.gif', '.webp']; // 支持的图片格式 // 递归遍历文件夹,收集图片路径 function collectImagePaths(dir) { let paths = []; const files = fs.readdirSync(dir); files.forEach(file => { const fullPath = path.join(dir, file); const fileStat = fs.statSync(fullPath); if (fileStat.isDirectory()) { // 递归处理子文件夹 paths = paths.concat(collectImagePaths(fullPath)); } else { const fileExt = path.extname(file).toLowerCase(); if (allowedImageExts.includes(fileExt)) { // 转换为项目中可访问的相对路径(适配public目录) const relativePath = path.relative('public', fullPath).replace(/\\/g, '/'); paths.push(`/${relativePath}`); } } }); return paths; } // 生成数组并写入文件 const imagePathsArray = collectImagePaths(imgFolderPath); const exportCode = `export const publicImageArray = ${JSON.stringify(imagePathsArray, null, 2)};`; fs.writeFileSync(outputFilePath, exportCode); console.log(`已完成!共收集${imagePathsArray.length}张图片,数组文件已生成至${outputFilePath}`);
使用步骤:
- 将脚本保存为
generateImageArray.js放在项目根目录 - 调整
imgFolderPath和outputFilePath为你的项目实际路径 - 运行命令:
node generateImageArray.js - 在项目中导入使用:
import { publicImageArray } from './src/imageArray.js'
场景2:Vite项目动态收集(无需额外脚本)
Vite原生支持import.meta.glob,可在代码中直接批量获取图片路径:
// 匹配public/images下所有图片,可根据需要修改路径和格式 const imageModules = import.meta.glob('/public/images/**/*.{jpg,jpeg,png,gif,webp}', { eager: true, as: 'url' }); // 转换为数组格式 export const publicImageArray = Object.values(imageModules);
场景3:Webpack项目动态收集(无需额外脚本)
Webpack通过require.context实现批量导入:
// 配置参数:图片文件夹相对路径、是否遍历子文件夹、匹配的图片格式 const imageContext = require.context('../public/images', true, /\.(jpg|jpeg|png|gif|webp)$/); // 将上下文转换为路径数组 export const publicImageArray = imageContext.keys().map(key => imageContext(key));
内容的提问来源于stack exchange,提问作者Karma idk
相关产品推荐
相关产品推荐

