Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling image paths in css files when processed by gulp

Previously in my MVC apps, I've used .NET to optimize (concatenate, minify, etc.) my CSS files. I've had to use custom transform classes to handle paths in my CSS like:

.brand {
    background-image: url("../images/logo.png");
}

or even:

.brand {
    background-image: url("/Content/images/logo.png");
}

I've added gulp to my most recent project for front-end testing and I thought I'd also use it to automatically optimize my CSS and JS files. Here is my gulp task to process CSS files:

var gulp = require('gulp');
var concat = require('gulp-concat');
var cssmin = require('gulp-minify-css');
var rename = require("gulp-rename");
var less = require('gulp-less');
var uglify = require('gulp-uglify');

gulp.task('styles', function () {
    return gulp.src('./Content/custom/site.less')
        .pipe(less())
        .pipe(gulp.dest('./dist/css'))
        .pipe(cssmin())
        .pipe(rename({
            suffix: '.min'
        }))
        .pipe(gulp.dest('./dist/css'));
});

The CSS file is minified, uglified, etc. successfully, but links to images, for example, are incorrect. Relative paths of course now reference something like http://localhost/site-folder/dist/css/Content/images/logo. Paths that were originally something like /Content/images/logo.png end up being http://localhost/Content/images/logo.png, but unfortunately, they don't account for domain folders which my site has.

Any ideas?

Thanks in advance

like image 975
im1dermike Avatar asked Jul 16 '15 13:07

im1dermike


Video Answer


1 Answers

The simplest way would be to use gulp-replace in a pipe for your css, and replace your current urls with the new image address. (I also added gulp-load-plugins to reduce require() bloat.

This assumes you're migrating the images as well in a separate task.

var gulp = require('gulp'),
    plugins = require('gulp-load-plugins'); // replaces all your requires

var yourDirectory = "/Content/images/";

gulp.task('styles', function () {
    return gulp.src('./Content/custom/site.less')
        .pipe(plugins.less())
        .pipe(gulp.dest('./dist/css'))
        .pipe(plugins.replace('url("../images/', 'url("' + yourDirectory)
        .pipe(plugins.cssmin())
        .pipe(plugins.rename({
            suffix: '.min'
        }))
        .pipe(gulp.dest('./dist/css'));
});
like image 171
Jared Hooper Avatar answered Oct 02 '22 19:10

Jared Hooper