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
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'));
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With