Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A Grunt string-replace task option for replacing CSS url() paths.
{
pattern: /url\((.*?)\)/ig,
replacement: function (match, p1, offset, string) {
var path, pathParts, pathLength, filename, newPath;
path = p1.replace(/["']/g,''); // Removes quotation marks if there are any
pathParts = path.split('/'); // Splits the path so we can find the filename
pathLength = pathParts.length;
filename = pathParts[pathLength-1]; // The filename is the last item in pathParts
// Rewrite the path based on the file type
// Note that .svg can be a font or a graphic, not sure what to do about this.
if (filename.indexOf('.eot') !== -1 ||
filename.indexOf('.woff') !== -1 ||
filename.indexOf('.ttf') !== -1 ||
filename.indexOf('.svg') !== -1)
{
newPath = 'url("../fonts/'+filename+'")';
grunt.verbose.ok('Replaced:',match,'\n with:',newPath);
grunt.verbose.writeln('');
return newPath;
} else if (filename.indexOf('.png') !== -1 ||
filename.indexOf('.gif') !== -1 ||
filename.indexOf('.jpg') !== -1)
{
newPath = 'url("../img/'+filename+'")';
grunt.verbose.ok('Replaced:',match,'\n with:',newPath);
grunt.verbose.writeln('');
return newPath;
} else {
grunt.verbose.warn('No filetype matches for:',match,'\n');
grunt.verbose.writeln('');
return match;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.