RainerD
RainerD

Reputation: 13

gulp-cssmin: How to change relative URLs in minified CSS

I'm new to gulp and need your help with the gulp-cssmin plugin to minify my CSS files. My simple project structure:

gulpfile.js
  css/
    myCss.css
    min/
      myCss.min.css
  images/
    myImg.jpg

My goal is now to minify the CSS file myCSS.css in folder css/, rename it to myCSS.min.css and copy it to folder css/min/. This is working as expected. Now I'm using relative URL paths in my CSS file:

background-image: url("../images/myImg.jpg");

When copying the file to folder css/min/, the path is no longer correct. I need to rebase the URL. How do I do this? I've tried to set the target option, with no effect. My gulpfile.js:

var gulp = require('gulp');
var cssmin = require('gulp-cssmin');
var rename = require('gulp-rename');

gulp.task('default', function () {
    gulp.src('css/*.css')
        .pipe(cssmin({ showLog: true, target: '../', keepBreaks: true }))
        .pipe(rename({ suffix: '.min' }))
        .pipe(gulp.dest('css/min'));
});

Upvotes: 1

Views: 1663

Answers (1)

Sven Schoenung
Sven Schoenung

Reputation: 30574

You need two options:

  • relativeTo: the folder where your input files are located (i.e. css/)
  • target: the folder that your output files are written to (i.e. css/min/)

So you end up with:

gulp.task('default', function () {
  gulp.src('css/*.css')
   .pipe(cssmin({ 
      showLog: true, 
      relativeTo: 'css/',
      target: 'css/min/', 
      keepBreaks: true
    }))
   .pipe(rename({ suffix: '.min' }))
   .pipe(gulp.dest('css/min'));
});

Upvotes: 1

Related Questions