Use Grunt to Find Unused Images

Published 3rd March 2014

Here is something that I just threw together that may come in handy. I was looking for an easy to way find unused images in your project without doing a manual “Find in Files” for each image. So I figured a custom Grunt task might be an simple way to achieve this.

Simply drop this code in your Gruntfile.js then run it using grunt unusedimages.

// Find unused images grunt.registerTask('unusedimages', function(){ var assets = [], links = []; // Get list of images grunt.file.expand({ filter: 'isFile', cwd: 'assets/images/' // Change this to your images dir }, ['**/*']).forEach(function(file){ assets.push(file); }); // Find images in content grunt.file.expand({ filter: 'isFile', }, ['assets/scripts/**/*.js', 'assets/styles/**/*.css']).forEach(function(file){ // Change this to narrow down the search var content = grunt.file.read(file); assets.forEach(function(asset){ if(content.search(asset) !== -1){ links.push(asset); } }); }); // Output unused images var unused = grunt.util._.difference(assets, links); console.log('Found '+ unused.length +' unused images:'); unused.forEach(function(el){ console.log(el); }); });

Note: This script doesn’t actually delete the unused images (as there may be false positives) but simply lists the unused images.